diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index d10f7ec2..a883bdaf 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -187,6 +187,18 @@ class Kernel extends ConsoleKernel ->withoutOverlapping(300) ->appendOutputTo(storage_path('logs/jst-sync-shipping.log')) ->runInBackground(); + // 发货数据常在次日上午继续补登。白天只按 updatedAt 补最近 7 天变化, + // 不再重复扫描整个数百万行发货视图,避免节点繁忙时超时并让页面停在半旧数据。 + $schedule->command('jushuitan:sync-shipping --days=7 --changes-only') + ->dailyAt('07:28') + ->withoutOverlapping(60) + ->appendOutputTo(storage_path('logs/jst-sync-shipping.log')) + ->runInBackground(); + $schedule->command('jushuitan:sync-shipping --days=7 --changes-only') + ->dailyAt('13:28') + ->withoutOverlapping(60) + ->appendOutputTo(storage_path('logs/jst-sync-shipping.log')) + ->runInBackground(); // 凌晨副本库最近一两天的商品明细常未到齐(出库单常在发货次日下午才确认,视图随后才有商品); // 白天副本库负载高、查询常超时断开,补拉放到晚上:每天 21:28 再拉最近 3 天, // 补齐凌晨只写入单号、缺商品明细的包裹。 diff --git a/modules/EcommerceFinance/Console/SyncJushuitanShipping.php b/modules/EcommerceFinance/Console/SyncJushuitanShipping.php index 2b1c4cc8..4cd4164f 100644 --- a/modules/EcommerceFinance/Console/SyncJushuitanShipping.php +++ b/modules/EcommerceFinance/Console/SyncJushuitanShipping.php @@ -11,6 +11,7 @@ use Modules\EcommerceFinance\Services\Jushuitan\ShippingReplicaSynchronizer; * * php artisan jushuitan:sync-shipping --from=2026-09-01 --to=2026-09-17 # 按发货时间窗口拉全量 * php artisan jushuitan:sync-shipping --days=3 # 滚动最近 3 天(每日调度用) + * php artisan jushuitan:sync-shipping --days=7 --changes-only # 只补最近变化 * php artisan jushuitan:sync-shipping # 最近 2000 条(快速看效果) * * 按 id 去重 upsert,任何时候补拉早期区间都不会重复。 @@ -18,7 +19,8 @@ use Modules\EcommerceFinance\Services\Jushuitan\ShippingReplicaSynchronizer; class SyncJushuitanShipping extends Command { protected $signature = 'jushuitan:sync-shipping {--from=} {--to=} {--days=} {--limit=2000} - {--skip-freight : 仅补发货数量;保留已有运费,新记录运费留空并标记部分完成}'; + {--skip-freight : 仅补发货数量;保留已有运费,新记录运费留空并标记部分完成} + {--changes-only : 按聚水潭 updatedAt 补最近变化,不扫描整个发货历史}'; protected $description = '从经营分析副本库直读聚水潭发货明细,清洗写入 caiwu 发货数据表'; @@ -37,10 +39,15 @@ class SyncJushuitanShipping extends Command } $skipFreight = (bool) $this->option('skip-freight'); + $changesOnly = (bool) $this->option('changes-only'); if ($skipFreight && (! $from || ! $to)) { $this->error('--skip-freight 需要指定 --from 和 --to,或使用 --days。'); return self::FAILURE; } + if ($changesOnly && (! $from || ! $to)) { + $this->error('--changes-only 需要指定 --from 和 --to,或使用 --days。'); + return self::FAILURE; + } $limit = (int) ($this->option('limit') ?: 2000); @@ -53,7 +60,14 @@ class SyncJushuitanShipping extends Command } }; try { - $result = ShippingReplicaSynchronizer::make()->sync($from, $to, $limit, $progress, $skipFreight); + $result = ShippingReplicaSynchronizer::make()->sync( + $from, + $to, + $limit, + $progress, + $skipFreight, + $changesOnly, + ); } catch (\Throwable $e) { $this->error('同步失败:' . $e->getMessage()); return self::FAILURE; @@ -85,6 +99,9 @@ class SyncJushuitanShipping extends Command if (($result['packages_items_corrected'] ?? 0) > 0 || ($result['amounts_matched_by_barcode'] ?? 0) > 0) { $this->info(sprintf('商品已更正并覆盖旧记录 %d 个包裹;按条码沿用旧金额 %d 行。', $result['packages_items_corrected'] ?? 0, $result['amounts_matched_by_barcode'] ?? 0)); } + if (($result['warehouses_backfilled'] ?? 0) > 0) { + $this->info(sprintf('空仓库已按出库单/订单仓库回填 %d 行。', $result['warehouses_backfilled'])); + } if (($result['packages_retained_for_unmatched_amount'] ?? 0) > 0) { $this->warn('其中 ' . $result['packages_retained_for_unmatched_amount'] . ' 个包裹因商品金额无法安全匹配而保留原记录,金额待核对。'); } diff --git a/modules/EcommerceFinance/Services/Jushuitan/ShippingReplicaSynchronizer.php b/modules/EcommerceFinance/Services/Jushuitan/ShippingReplicaSynchronizer.php index 2455fcb0..b0a3f58a 100644 --- a/modules/EcommerceFinance/Services/Jushuitan/ShippingReplicaSynchronizer.php +++ b/modules/EcommerceFinance/Services/Jushuitan/ShippingReplicaSynchronizer.php @@ -4,6 +4,7 @@ namespace Modules\EcommerceFinance\Services\Jushuitan; use Illuminate\Support\Carbon; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Schema; use InvalidArgumentException; use Modules\EcommerceFinance\Services\UpstreamConnection; use Modules\EcommerceFinance\Services\UpstreamReadOnlyQueryFactory; @@ -38,6 +39,8 @@ class ShippingReplicaSynchronizer private const PURCHASE_OUT_OFFSET = 3000000000; private const DEMO_SOURCE_IDS = [9000001, 9000002, 9000003, 9000004, 9000005, 9000006]; private const FLUSH = 300; + /** 发货明细和订单发货日期偶有一周内偏差;该缓存只用于阻止 auto-ship 重复补同一订单。 */ + private const AUTOSHIP_DETAIL_GUARD_SECONDS = 604800; private const PRESERVED_PACKAGE_FIELDS = [ 'buyer_nick', 'seller_memo', 'package_no', 'download_time', 'freight_rate', 'freight_formula', 'settle_volume_cm3', 'recon_weight_kg', 'recon_volume_cm3', 'front_no', @@ -166,6 +169,9 @@ class ShippingReplicaSynchronizer /** @var array> wms_co_id => [仓库名 => 次数]:从快递公司一致的发货明细行学习仓库名 */ private array $wmsNames = []; + /** @var array wms_co_id => 仓库档案名称 */ + private array $warehouseDirectory = []; + /** @var array 包裹 source_id => 出库单 wms_co_id(扫描结束后按学到的仓库名统一回填) */ private array $pendingWarehouse = []; @@ -187,9 +193,6 @@ class ShippingReplicaSynchronizer /** @var array 最近一次 loadViewItems 的 io_id => 视图发货仓 wareHoursName(工作平台显示的仓库) */ private array $ioWare = []; - /** @var array 已查询订单元数据缓存 o_id=>字段 */ - private array $orderMetadata = []; - /** @var array 窗口内出库单映射(见 emptyIoMap) */ private array $outboundMap = ['byL' => [], 'byO' => [], 'byLO' => [], 'byOAll' => [], 'ioL' => []]; @@ -206,7 +209,14 @@ class ShippingReplicaSynchronizer return new self(app(UpstreamReadOnlyQueryFactory::class)); } - public function sync(?Carbon $from = null, ?Carbon $to = null, int $limit = 2000, ?callable $progress = null, bool $skipFreight = false): array + public function sync( + ?Carbon $from = null, + ?Carbon $to = null, + int $limit = 2000, + ?callable $progress = null, + bool $skipFreight = false, + bool $changesOnly = false, + ): array { $this->markRunning(); try { @@ -214,6 +224,9 @@ class ShippingReplicaSynchronizer if ($skipFreight && ! $windowed) { throw new InvalidArgumentException('跳过运费仅支持指定起止日期的历史补录。'); } + if ($changesOnly && ! $windowed) { + throw new InvalidArgumentException('仅补变化数据需要指定起止日期。'); + } $this->skipFreight = $skipFreight; // Only an explicit date window is a replacement run. The regular incremental // path keeps its existing fast upsert semantics and does not rescan old parcels. @@ -263,10 +276,12 @@ class ShippingReplicaSynchronizer $this->ioWeight = []; $this->ioFWeight = []; $this->wmsNames = []; + $this->warehouseDirectory = []; $this->pendingWarehouse = []; $this->ioOk = []; $this->pairingSkipped = 0; if ($windowed) { + $this->preloadWarehouseDirectory(); $this->preloadDws($from, $to); $this->preloadOutboundMap($fromS, $toS); if ($progress) { @@ -277,13 +292,13 @@ class ShippingReplicaSynchronizer count($this->outboundMap['byO']), )); } - $total = $this->syncExpress(true, $fromS, $toS, $limit, $now, $progress); + $total = $this->syncExpress(true, $fromS, $toS, $limit, $now, $progress, $changesOnly); $this->applyPendingWarehouses($progress); - $this->orderMetadata = []; // 全表扫描后释放(数百万订单),后续各步不再使用 gc_collect_cycles(); $auto = $this->syncAutoShip($fromS, $toS, $now, $progress); $outb = $this->syncOutbound($fromS, $toS, $now, $progress); $pout = $this->syncPurchaseOut($fromS, $toS, $now, $progress); + $warehousesBackfilled = $this->backfillMissingWarehouses($fromS, $toS, $progress); $purged = $this->purgeExcludedPackages($fromS, $toS); $platformFixed = $this->normalizePlatformCodes($fromS, $toS); if ($progress && $platformFixed > 0) { @@ -292,7 +307,7 @@ class ShippingReplicaSynchronizer if ($progress && $purged > 0) { $progress('清除已排除包裹(取消/拆分/合并/线上发货):' . $purged . ' 行'); } - $this->staleMirrorPackages = $this->countUnseenMirrorPackages($fromS, $toS); + $this->staleMirrorPackages = $changesOnly ? 0 : $this->countUnseenMirrorPackages($fromS, $toS); if (! $skipFreight && $this->staleMirrorPackages === 0) { $removed = $this->dedupAtPrefix($fromS, $toS); if ($progress && $removed > 0) { @@ -350,14 +365,14 @@ class ShippingReplicaSynchronizer $this->applyPendingWarehouses($progress); } - if ($windowed && ! $skipFreight && $this->staleMirrorPackages === 0) { + if ($windowed && ! $changesOnly && ! $skipFreight && $this->staleMirrorPackages === 0) { $this->markCovered(self::FREIGHT_DATASET_PREFIX, $fromS, $toS); } - if ($windowed && ($this->dwsFailedDays !== [] || $this->packagesWithoutItems > 0 + if ($windowed && ! $changesOnly && ($this->dwsFailedDays !== [] || $this->packagesWithoutItems > 0 || $this->packagesRetainedForUnmatchedAmount > 0)) { $this->markItemsIncomplete($fromS, $toS); - } elseif ($windowed && ! $skipFreight && $this->staleMirrorPackages === 0) { + } elseif ($windowed && ! $changesOnly && ! $skipFreight && $this->staleMirrorPackages === 0) { $this->markCovered(self::ITEMS_DATASET_PREFIX, $fromS, $toS); } @@ -379,6 +394,7 @@ class ShippingReplicaSynchronizer $result['ship_time_fixed'] = $this->shipTimeFixed; $result['weight_fixed'] = $this->weightFixed; $result['placeholder_packages_cleaned'] = $this->placeholderPurged; + $result['warehouses_backfilled'] = $warehousesBackfilled; } if ($skipFreight) { $result['freight_incomplete'] = true; @@ -395,7 +411,6 @@ class ShippingReplicaSynchronizer throw $e; } finally { $this->dwsCache = []; - $this->orderMetadata = []; $this->outboundMap = ['byL' => [], 'byO' => [], 'byLO' => [], 'byOAll' => [], 'ioL' => []]; $this->replacementPackages = []; $this->replacementHasFreight = []; @@ -463,13 +478,21 @@ class ShippingReplicaSynchronizer } /** 主口径:发货单(dlv 镜像) × 每件商品。 */ - private function syncExpress(bool $windowed, ?string $fromS, ?string $toS, int $limit, $now, ?callable $progress = null): int + private function syncExpress( + bool $windowed, + ?string $fromS, + ?string $toS, + int $limit, + $now, + ?callable $progress = null, + bool $changesOnly = false, + ): int { $batch = 1500; $maxBatches = $this->maxExpressBatches; - $cols = 'e.id, e.so_id, e.inner_order_id, e.logistic_id, e.logistic_company_name, e.send_time, e.pay_time, ' + $cols = 'e.id, e.updatedAt, e.so_id, e.inner_order_id, e.logistic_id, e.logistic_company_name, e.send_time, e.pay_time, ' . 'e.shop_name, e.platform_name, e.dis_co_name, e.warehouse_name, e.receiver_address, ' - . 'e.weight, e.f_weight, e.buyer_message, e.order_labels'; + . 'e.weight, e.f_weight, e.buyer_message, e.order_status_name, e.order_labels'; // 窗口模式:只按主键 e.id 翻页(有索引,毫秒级),send_time 窗口过滤放到 PHP, // 避免每页都对无索引的 send_time 做全表扫描(那是"卡死"的真凶)。 @@ -479,15 +502,27 @@ class ShippingReplicaSynchronizer $total = 0; $scanned = 0; $lastId = null; + $changeCursor = null; for ($b = 0; $b <= $maxBatches; $b++) { - $where = $windowed ? '1 = 1' : 'e.send_time IS NOT NULL'; - $bind = []; - if ($lastId !== null) { - $where .= ' AND e.id < ?'; - $bind[] = $lastId; + if ($changesOnly) { + $where = 'e.updatedAt >= ? AND e.updatedAt < ?'; + $bind = [$fromS, $toS]; + if ($changeCursor !== null) { + $where .= ' AND (e.updatedAt < ? OR (e.updatedAt = ? AND e.id < ?))'; + array_push($bind, $changeCursor['updatedAt'], $changeCursor['updatedAt'], $changeCursor['id']); + } + $sql = "SELECT TOP {$batch} {$cols} FROM rpt.jst_order_express_details e " + . "WHERE {$where} ORDER BY e.updatedAt DESC, e.id DESC"; + } else { + $where = $windowed ? '1 = 1' : 'e.send_time IS NOT NULL'; + $bind = []; + if ($lastId !== null) { + $where .= ' AND e.id < ?'; + $bind[] = $lastId; + } + $sql = "SELECT TOP {$batch} {$cols} FROM rpt.jst_order_express_details e " + . "WHERE {$where} ORDER BY e.id DESC"; } - $sql = "SELECT TOP {$batch} {$cols} FROM rpt.jst_order_express_details e " - . "WHERE {$where} ORDER BY e.id DESC"; $rows = $this->selectWithReconnect($sql, $bind); if ($rows === []) { break; @@ -499,26 +534,25 @@ class ShippingReplicaSynchronizer $scanned += $cnt; foreach ($rows as $r) { $lastId = $r['id']; + if ($changesOnly) { + $changeCursor = [ + 'updatedAt' => $r['updatedAt'] ?? null, + 'id' => (int) ($r['id'] ?? 0), + ]; + } } - // 主表分页不联接订单表;每页只按 inner_order_id 分块补齐订单字段, - // 并复用已经缓存的结果,避免 LEFT JOIN 在大历史窗口上拖垮游标。 - $this->loadOrderMetadataForRows($rows); - $rows = array_map(fn (array $row): array => $this->mergeOrderMetadata($row), $rows); - if ($windowed) { $kept = []; foreach ($rows as $r) { - $jd = $r['jo_send'] ?? null; - $joTs = ($jd !== null && $jd !== '') ? strtotime((string) $jd) : null; - $oid = (string) ($r['inner_order_id'] ?? ''); - if ($oid !== '' && $joTs !== null && $joTs !== false && $joTs >= $fromTs && $joTs < $toTs) { - $this->expressOrderIds[$oid] = true; - } $st = $r['send_time'] ?? null; $ts = ($st !== null && $st !== '') ? strtotime((string) $st) : null; - if ($ts === null) { - $ts = $joTs; + $oid = (string) ($r['inner_order_id'] ?? ''); + if ($oid !== '' && $ts !== null + && $ts >= $fromTs - self::AUTOSHIP_DETAIL_GUARD_SECONDS + && $ts < $toTs + self::AUTOSHIP_DETAIL_GUARD_SECONDS) { + // 已有快递明细的订单不能再走 auto-ship;保留一周边界,兼容次日出库、换单等偏差。 + $this->expressOrderIds[$oid] = true; } if ($ts !== null && $ts >= $fromTs && $ts < $toTs) { $kept[] = $r; @@ -573,7 +607,7 @@ class ShippingReplicaSynchronizer if ($pkgId === 0) { continue; } - if (in_array((string) ($r['jo_status'] ?? ''), ['Cancelled', 'Split', 'Merged'], true)) { + if ($this->excludedOrderStatus($r['order_status_name'] ?? $r['jo_status'] ?? null)) { // 订单已取消/已拆分/已合并:实际发货在子单或合并单上,工作平台不出此行。 // 只登记本行自己的单号,不登记订单单号(可能是子单真实单号,需留给出库单兜底) $this->markDone('', (string) ($r['logistic_id'] ?? '')); @@ -592,7 +626,8 @@ class ShippingReplicaSynchronizer $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); + $excluded = $this->excludedByLabel($r['order_labels'] ?? null) + || $this->excludedByLabel($r['jo_labels'] ?? null); if ($excluded) { $this->markTrackSo($so, 0, $lid, $orderLid); $this->excludeSource($pkgId); @@ -641,69 +676,6 @@ class ShippingReplicaSynchronizer return $total; } - /** 按当前页订单键补齐订单字段,并复用已缓存的结果。 */ - private function loadOrderMetadataForRows(array $rows): void - { - $oids = []; - foreach ($rows as $row) { - $oid = (string) ($row['inner_order_id'] ?? ''); - if ($oid !== '' && ! array_key_exists($oid, $this->orderMetadata)) { - $oids[$oid] = true; - } - } - foreach (array_chunk(array_keys($oids), 400) as $chunk) { - if ($chunk === []) { - continue; - } - $ph = implode(',', array_fill(0, count($chunk), '?')); - $sql = "SELECT o_id, l_id, send_date, status, labels, shop_name FROM rpt.jst_Orders om WHERE om.o_id IN ({$ph})"; - foreach ($this->selectWithReconnect($sql, $chunk) as $row) { - $oid = (string) ($row['o_id'] ?? ''); - if ($oid === '') { - continue; - } - // 全表扫描会缓存数百万订单:只留判断需要的精简字段(状态仅存会被排除的三种,标签只存是否线上发货) - $st = (string) ($row['status'] ?? ''); - $this->orderMetadata[$oid] = [ - 'l_id' => $row['l_id'] ?? null, - 'send_date' => $row['send_date'] ?? null, - 'shop_name' => $row['shop_name'] ?? null, - 'status' => in_array($st, ['Cancelled', 'Split', 'Merged'], true) ? $st : null, - 'online' => $this->excludedByLabel($row['labels'] ?? null), - ]; - } - foreach ($chunk as $oid) { - // 记录无匹配订单,避免后续分页反复查询同一个缺失键。 - $this->orderMetadata[$oid] ??= ['l_id' => null, 'send_date' => null, 'status' => null, 'online' => false]; - } - } - } - - /** 将订单元数据映射到发货明细,保留测试/兼容来源已提供的字段。 */ - private function mergeOrderMetadata(array $row): array - { - $oid = (string) ($row['inner_order_id'] ?? ''); - $metadata = $oid !== '' ? ($this->orderMetadata[$oid] ?? []) : []; - if (($row['jo_lid'] ?? '') === '' && ($metadata['l_id'] ?? '') !== '') { - $row['jo_lid'] = $metadata['l_id']; - } - if (($row['jo_send'] ?? '') === '' && ($metadata['send_date'] ?? '') !== '') { - $row['jo_send'] = $metadata['send_date']; - } - if (trim((string) ($row['shop_name'] ?? '')) === '' && ! empty($metadata['shop_name'])) { - $row['shop_name'] = $metadata['shop_name']; - } - // 订单状态/标签:取消/拆分/合并 与 订单级"线上发货"标签的排除判断用 - if (($row['jo_status'] ?? '') === '' && ($metadata['status'] ?? '') !== '') { - $row['jo_status'] = $metadata['status']; - } - if (($row['jo_labels'] ?? '') === '' && ! empty($metadata['online'])) { - $row['jo_labels'] = '线上发货'; - } - - return $row; - } - /** @return list> */ private function selectWithReconnect(string $sql, array $bindings): array { @@ -745,7 +717,7 @@ class ShippingReplicaSynchronizer $cols = 'o.Id AS rid, o.o_id, o.so_id, o.l_id, o.logistics_company, o.order_from, o.labels, ' . 'o.shop_name, o.send_date, o.pay_date, o.weight, o.buyer_message, ' . 'o.receiver_state, o.receiver_city, o.receiver_district, o.receiver_address, ' - . 'o.receiver_name, o.receiver_mobile, o.receiver_phone'; + . 'o.receiver_name, o.receiver_mobile, o.receiver_phone, o.wms_co_id'; $total = 0; $lastRid = null; @@ -838,6 +810,7 @@ class ShippingReplicaSynchronizer $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->withIoWeight($io, $this->pkgFromOrder($r, $tracking, $shipTime)); + $pkg = $this->withWmsWarehouse($pkg); $pkg['platform'] = $this->platformOf($io, $pkg['platform']); $pkg = $this->withViewAddr($io, $pkg); $pkg = $this->withViewCarrier($io, $pkg, $pkgId); @@ -1613,6 +1586,9 @@ class ShippingReplicaSynchronizer private function wmsName(string $wms): ?string { + if (isset($this->warehouseDirectory[$wms])) { + return $this->warehouseDirectory[$wms]; + } if (empty($this->wmsNames[$wms])) { return null; } @@ -1628,6 +1604,148 @@ class ShippingReplicaSynchronizer return (string) array_key_first($names); } + /** 聚水潭仓库档案是稳定维表,先预载后可把订单/出库单上的 wms_co_id 直接还原成仓库名。 */ + private function preloadWarehouseDirectory(): void + { + if (! Schema::connection('business_mirror')->hasTable('ops_jst_warehouse_info')) { + return; + } + $rows = DB::connection('business_mirror')->table('ops_jst_warehouse_info') + ->whereNotNull('wms_co_id') + ->orderBy('Id') + ->get(['wms_co_id', 'name']); + foreach ($rows as $row) { + $wms = trim((string) ($row->wms_co_id ?? '')); + $name = $this->whName($row->name ?? null); + if ($wms !== '' && $wms !== '0' && $name !== null) { + $this->warehouseDirectory[$wms] = $name; + } + } + } + + /** 自动发货单没有出库视图时,用订单上的 wms_co_id 还原仓库。 */ + private function withWmsWarehouse(array $pkg): array + { + if ($this->whName($pkg['warehouse_name'] ?? null) !== null) { + return $pkg; + } + $wms = trim((string) ($pkg['wms_co_id'] ?? '')); + $name = $wms !== '' && $wms !== '0' ? $this->wmsName($wms) : null; + if ($name !== null) { + $pkg['warehouse_name'] = $name; + } + + return $pkg; + } + + /** + * 已写镜像但仓库为空的历史包裹,按出库单/订单的 wms_co_id 或发货视图重新回填。 + * 只处理当前日期窗口,不中断主同步;这些行此前会被供应商货款预估的“代发仓”条件漏掉。 + */ + private function backfillMissingWarehouses(string $fromS, string $toS, ?callable $progress = null): int + { + $rows = $this->db->table('jst_oms_shipping') + ->where('ship_time', '>=', $fromS) + ->where('ship_time', '<', $toS) + ->where(function ($query): void { + $query->whereNull('warehouse_name')->orWhere('warehouse_name', ''); + }) + ->get(['source_id', 'express_no', 'trade_no']); + if ($rows->isEmpty()) { + return 0; + } + + $byName = []; + $pendingByIo = []; + foreach ($rows as $row) { + $sourceId = (int) ($row->source_id ?? 0); + $io = ''; + if ($sourceId >= self::OUTBOUND_OFFSET && $sourceId < self::PURCHASE_OUT_OFFSET) { + $io = (string) ($sourceId - self::OUTBOUND_OFFSET); + } else { + $tracking = ltrim(trim((string) ($row->express_no ?? '')), '@'); + $tradeNo = trim((string) ($row->trade_no ?? '')); + $io = $tracking !== '' ? (string) ($this->outboundMap['byLO'][$tracking . '|' . $tradeNo] + ?? $this->outboundMap['byL'][$tracking] + ?? '') : ''; + // 自动发货单换取单号后可能只有内部订单能定位;仅在唯一出库单时回填仓库。 + if ($io === '' && $sourceId >= self::AUTOSHIP_OFFSET && $sourceId < self::OUTBOUND_OFFSET) { + $orderIo = $this->outboundMap['byOAll'][(string) ($sourceId - self::AUTOSHIP_OFFSET)] ?? []; + if (count($orderIo) === 1) { + $io = (string) array_key_first($orderIo); + } + } + } + if ($io === '') { + continue; + } + $name = $this->whName($this->ioWare[$io] ?? null) ?? $this->wmsName((string) ($this->ioWms[$io] ?? '')); + if ($name !== null) { + $byName[$name][] = $sourceId; + continue; + } + $pendingByIo[$io][] = $sourceId; + } + + if (! empty($pendingByIo)) { + try { + $this->loadViewWarehouses(array_keys($pendingByIo)); + foreach ($pendingByIo as $io => $sourceIds) { + $name = $this->whName($this->ioWare[(string) $io] ?? null) + ?? $this->wmsName((string) ($this->ioWms[(string) $io] ?? '')); + if ($name !== null) { + $byName[$name] = array_merge($byName[$name] ?? [], $sourceIds); + } + } + } catch (Throwable $e) { + if ($progress) { + $progress('仓库补全视图查询跳过:' . mb_substr($e->getMessage(), 0, 160)); + } + } + } + + $updated = 0; + foreach ($byName as $name => $sourceIds) { + foreach (array_chunk(array_values(array_unique($sourceIds)), 500) as $chunk) { + $updated += (int) $this->db->table('jst_oms_shipping') + ->whereIn('source_id', $chunk) + ->where('ship_time', '>=', $fromS) + ->where('ship_time', '<', $toS) + ->where(function ($query): void { + $query->whereNull('warehouse_name')->orWhere('warehouse_name', ''); + }) + ->update(['warehouse_name' => $name]); + } + } + if ($progress && $updated > 0) { + $progress(sprintf('仓库补全:%d 个空仓库包裹,更新 %d 行', count($rows), $updated)); + } + + return $updated; + } + + /** 逐批读取发货视图的仓库名;比加载整包商品轻,专门用于历史空仓库修复。 */ + private function loadViewWarehouses(array $ioIds): void + { + foreach (array_chunk(array_values(array_unique(array_filter($ioIds))), 100) as $chunk) { + if ($chunk === []) { + continue; + } + $ph = implode(',', array_fill(0, count($chunk), '?')); + $rows = $this->selectWithReconnect( + 'SELECT io_id, wareHoursName FROM ' . self::VIEW . " WHERE io_id IN ({$ph})", + $chunk, + ); + foreach ($rows as $row) { + $io = trim((string) ($row['io_id'] ?? '')); + $name = $this->whName($row['wareHoursName'] ?? null); + if ($io !== '' && $name !== null) { + $this->ioWare[$io] = $name; + } + } + } + } + /** 扫描时还没学到仓库名的包裹:扫描结束后按学到的 wms_co_id => 仓库名统一回填。 */ private function applyPendingWarehouses(?callable $progress = null): void { @@ -1767,6 +1885,7 @@ class ShippingReplicaSynchronizer 'platform' => $r['order_from'] ?? null, 'dis_co_name' => null, 'warehouse_name' => null, + 'wms_co_id' => $r['wms_co_id'] ?? null, 'r_state' => $r['receiver_state'] ?? null, 'r_city' => $r['receiver_city'] ?? null, 'r_district' => $r['receiver_district'] ?? null, @@ -2065,7 +2184,8 @@ class ShippingReplicaSynchronizer /** 窗口同步按 io_date 一次预载,避免对无可用索引的 l_id/o_id 反复执行 IN 查询。 */ private function preloadOutboundMap(string $fromS, string $toS): void { - $sql = 'SELECT l_id, o_id, io_id, io_date, status, logistics_company, wms_co_id, weight, f_weight FROM ' . self::OUTBOUND . ' WHERE io_date >= ? AND io_date < ?'; + $sql = 'SELECT l_id, o_id, io_id, io_date, status, logistics_company, wms_co_id, weight, f_weight FROM ' + . self::OUTBOUND . ' WHERE io_date >= ? AND io_date < ?'; $this->outboundMap = $this->mapOutboundRows($this->selectOutbound($sql, [$fromS, $toS])); } @@ -2194,7 +2314,7 @@ class ShippingReplicaSynchronizer // 快递明细单号只对应作废出库单时,视为已换单(工作平台显示有效出库单的新单号) $hasValidIo = $byL !== null && ($this->ioOk[(string) $byL] ?? true); if ($lg === '' || $oid === '' || $hasValidIo || empty($ioMap['byOAll'][$oid]) - || in_array((string) ($r['jo_status'] ?? ''), ['Cancelled', 'Split', 'Merged'], true)) { + || $this->excludedOrderStatus($r['order_status_name'] ?? $r['jo_status'] ?? null)) { continue; } $need[] = $r; @@ -2888,6 +3008,20 @@ class ShippingReplicaSynchronizer return true; } + /** 明细视图的订单状态是中文;兼容历史/测试中的聚水潭枚举值。 */ + private function excludedOrderStatus(mixed $status): bool + { + $value = mb_strtolower(trim((string) ($status ?? ''))); + if ($value === '') { + return false; + } + if (in_array($value, ['cancelled', 'canceled', 'cancel', 'split', 'merged', 'delete', 'deleted'], true)) { + return true; + } + + return preg_match('/已取消|被取消|已拆分|被拆分|已合并|被合并|已删除|被删除/u', $value) === 1; + } + /** @return array sku_id => 尺寸/重量/供应商 */ private function loadSkus(array $skuIds): array { diff --git a/tests/Unit/EcommerceFinance/ShippingReplicaSynchronizerTest.php b/tests/Unit/EcommerceFinance/ShippingReplicaSynchronizerTest.php index 2e2afe4c..b02446fe 100644 --- a/tests/Unit/EcommerceFinance/ShippingReplicaSynchronizerTest.php +++ b/tests/Unit/EcommerceFinance/ShippingReplicaSynchronizerTest.php @@ -3,7 +3,9 @@ namespace Tests\Unit\EcommerceFinance; use Illuminate\Support\Carbon; +use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Schema; use Modules\EcommerceFinance\Services\Jushuitan\ShippingReplicaSynchronizer; use Modules\EcommerceFinance\Services\UpstreamReadOnlyQuery; use Modules\EcommerceFinance\Services\UpstreamReadOnlyQueryFactory; @@ -15,27 +17,31 @@ use Tests\TestCase; class ShippingReplicaSynchronizerTest extends TestCase { - public function test_windowed_express_scan_maps_order_metadata_without_joining_orders_per_page(): void + public function test_windowed_express_scan_uses_detail_fields_without_querying_orders(): void { $detailQueries = []; - $orderMetadataQueries = []; + $orderQueries = []; $detailCalls = 0; $upstream = $this->createMock(UpstreamReadOnlyQuery::class); - $upstream->method('select')->willReturnCallback(function (string $sql, array $bindings) use (&$detailQueries, &$orderMetadataQueries, &$detailCalls): array { + $upstream->method('select')->willReturnCallback(function (string $sql, array $bindings) use (&$detailQueries, &$orderQueries, &$detailCalls): array { if (str_contains($sql, 'FROM rpt.jst_order_express_details e')) { $detailQueries[] = $sql; return $detailCalls++ === 0 - ? [['id' => 5000, 'inner_order_id' => 'order-1', 'send_time' => null, 'logistic_id' => '']] + ? [[ + 'id' => 5000, + 'so_id' => 'trade-1', + 'inner_order_id' => 'order-1', + 'send_time' => '2026-09-02 12:00:00', + 'logistic_id' => 'order-tracking', + 'shop_name' => '供销店铺', + 'order_status_name' => '已发货', + 'order_labels' => null, + ]] : []; } if (str_contains($sql, 'FROM rpt.jst_Orders om WHERE om.o_id IN')) { - $orderMetadataQueries[] = [$sql, $bindings]; - - return [['o_id' => 'order-1', 'l_id' => 'order-tracking', 'send_date' => '2026-09-02 12:00:00', 'shop_name' => '供销店铺']]; - } - if (str_contains($sql, 'FROM rpt.jst_Orders o WHERE o.status =')) { - return []; + $orderQueries[] = [$sql, $bindings]; } return []; @@ -49,8 +55,7 @@ class ShippingReplicaSynchronizerTest extends TestCase $this->assertNotEmpty($detailQueries); $this->assertStringNotContainsString('LEFT JOIN rpt.jst_Orders', $detailQueries[0]); - $this->assertCount(1, $orderMetadataQueries); - $this->assertSame(['order-1'], $orderMetadataQueries[0][1]); + $this->assertSame([], $orderQueries); $this->assertSame(1, $result['processed']); $row = DB::connection('business_mirror')->table('jst_oms_shipping')->where('source_id', 5000)->sole(); $this->assertSame('order-tracking', $row->express_no); @@ -58,43 +63,90 @@ class ShippingReplicaSynchronizerTest extends TestCase $this->assertSame('供销店铺', $row->shop_name); } - public function test_order_metadata_timeout_retries_on_patient_connection_instead_of_failing_the_month(): void + public function test_windowed_express_excludes_cancelled_order_using_detail_status(): void { - // 2026-11、09 整月同步:按 IN 查 rpt.jst_Orders 在默认 15 秒连接上反复超时直到放弃;重试改走 120 秒连接 $detailCalls = 0; - $fastOrderQueries = 0; - $handler = function (bool $patient) use (&$detailCalls, &$fastOrderQueries) { - return function (string $sql, array $bindings) use ($patient, &$detailCalls, &$fastOrderQueries): array { - if (str_contains($sql, 'FROM rpt.jst_order_express_details e')) { - return $detailCalls++ === 0 ? [['id' => 5000, 'inner_order_id' => 'order-1', 'send_time' => null, 'logistic_id' => '']] : []; - } - if (str_contains($sql, 'FROM rpt.jst_Orders om WHERE om.o_id IN')) { - if (! $patient) { - $fastOrderQueries++; - throw new PDOException('SQLSTATE[HY000]: General error: 20003 Adaptive Server connection timed out [20003] (severity 6)'); - } + $upstream = $this->createMock(UpstreamReadOnlyQuery::class); + $upstream->method('select')->willReturnCallback(function (string $sql) use (&$detailCalls): array { + if (str_contains($sql, 'FROM rpt.jst_order_express_details e')) { + return $detailCalls++ === 0 + ? [[ + 'id' => 5001, + 'so_id' => 'trade-1', + 'inner_order_id' => 'order-1', + 'send_time' => '2026-09-02 12:00:00', + 'logistic_id' => 'cancelled-tracking', + 'order_status_name' => '已取消', + ]] + : []; + } - return [['o_id' => 'order-1', 'l_id' => 'order-tracking', 'send_date' => '2026-09-02 12:00:00', 'shop_name' => '供销店铺']]; - } - - return []; - }; - }; - $fast = $this->createMock(UpstreamReadOnlyQuery::class); - $fast->method('select')->willReturnCallback($handler(false)); - $patient = $this->createMock(UpstreamReadOnlyQuery::class); - $patient->method('select')->willReturnCallback($handler(true)); + return []; + }); $factory = $this->createMock(UpstreamReadOnlyQueryFactory::class); - $factory->method('forSource')->with('operations_replica')->willReturn($fast); - $factory->expects($this->once())->method('forSourceWithTimeout')->with('operations_replica', 120)->willReturn($patient); + $factory->method('forSource')->with('operations_replica')->willReturn($upstream); $result = (new ShippingReplicaSynchronizer($factory))->sync( Carbon::parse('2026-09-01'), Carbon::parse('2026-09-05'), 2000, null, true, ); - $this->assertSame(1, $fastOrderQueries); + $this->assertSame(0, $result['processed']); + $this->assertFalse(DB::connection('business_mirror')->table('jst_oms_shipping')->where('source_id', 5001)->exists()); + } + + public function test_changes_only_scan_filters_by_updated_at_and_preserves_unseen_history(): void + { + DB::connection('business_mirror')->table('jst_oms_shipping')->insert([ + 'source_id' => 4000, + 'sku_source_id' => 400000, + 'express_no' => 'old-but-valid', + 'ship_time' => '2026-09-02 10:00:00', + 'warehouse_name' => '工厂-测试代发仓', + ]); + $detailQueries = []; + $detailCalls = 0; + $upstream = $this->createMock(UpstreamReadOnlyQuery::class); + $upstream->method('select')->willReturnCallback(function (string $sql) use (&$detailQueries, &$detailCalls): array { + if (str_contains($sql, 'FROM rpt.jst_order_express_details e')) { + $detailQueries[] = $sql; + + return $detailCalls++ === 0 + ? [[ + 'id' => 5002, + 'updatedAt' => '2026-09-03 08:00:00', + 'so_id' => 'trade-2', + 'inner_order_id' => 'order-2', + 'send_time' => '2026-09-02 12:00:00', + 'logistic_id' => 'changed-tracking', + 'order_status_name' => '已发货', + ]] + : []; + } + + return []; + }); + $factory = $this->createMock(UpstreamReadOnlyQueryFactory::class); + $factory->method('forSource')->with('operations_replica')->willReturn($upstream); + + $result = (new ShippingReplicaSynchronizer($factory))->sync( + Carbon::parse('2026-09-01'), + Carbon::parse('2026-09-05'), + 2000, + null, + true, + true, + ); + + $this->assertNotEmpty($detailQueries); + $this->assertStringContainsString('e.updatedAt >= ? AND e.updatedAt < ?', $detailQueries[0]); $this->assertSame(1, $result['processed']); - $this->assertSame('order-tracking', DB::connection('business_mirror')->table('jst_oms_shipping')->where('source_id', 5000)->value('express_no')); + $this->assertSame(0, $result['stale_mirror_packages']); + $this->assertSame('succeeded', DB::connection('business_mirror')->table('jst_sync_state') + ->where('dataset_key', 'jst.sctrade')->value('status')); + $this->assertSame( + ['old-but-valid', 'changed-tracking'], + DB::connection('business_mirror')->table('jst_oms_shipping')->orderBy('source_id')->pluck('express_no')->all(), + ); } public function test_windowed_outbound_lookup_preloads_date_range_and_reuses_cache_without_in_queries(): void @@ -1343,6 +1395,90 @@ class ShippingReplicaSynchronizerTest extends TestCase $this->assertSame(0.0, $volume->invoke($sync, 10, 3, 2, 2.0, '普通仓', '中通礼品单')); } + public function test_auto_ship_resolves_daifa_warehouse_from_order_wms_id(): void + { + Schema::connection('business_mirror')->dropIfExists('ops_jst_warehouse_info'); + Schema::connection('business_mirror')->create('ops_jst_warehouse_info', function (Blueprint $table): void { + $table->unsignedBigInteger('Id'); + $table->string('wms_co_id'); + $table->string('name')->nullable(); + }); + DB::connection('business_mirror')->table('ops_jst_warehouse_info')->insert([ + 'Id' => 1, + 'wms_co_id' => '15137729', + 'name' => '工厂-河北雅柏代发仓', + ]); + + $detailCalls = 0; + $upstream = $this->createMock(UpstreamReadOnlyQuery::class); + $upstream->method('select')->willReturnCallback(function (string $sql) use (&$detailCalls): array { + if (str_contains($sql, 'FROM rpt.jst_order_express_details e')) { + return $detailCalls++ === 0 ? [] : []; + } + if (str_contains($sql, "FROM rpt.jst_Orders o WHERE o.status = 'Sent'")) { + return [[ + 'rid' => 3702509, + 'o_id' => '10416801', + 'so_id' => '3697437005510067', + 'l_id' => 'JDLD13294409324', + 'logistics_company' => '线下快递', + 'order_from' => '京东商城', + 'labels' => null, + 'shop_name' => '京东-全也家具旗舰店', + 'send_date' => '2026-11-30 13:28:29', + 'wms_co_id' => '15137729', + ]]; + } + + return []; + }); + $factory = $this->createMock(UpstreamReadOnlyQueryFactory::class); + $factory->method('forSource')->with('operations_replica')->willReturn($upstream); + + $result = (new ShippingReplicaSynchronizer($factory))->sync( + Carbon::parse('2026-11-30'), Carbon::parse('2026-12-01'), 2000, null, true, + ); + + $this->assertSame(1, $result['autoship']); + $row = DB::connection('business_mirror')->table('jst_oms_shipping') + ->where('source_id', 1010416801) + ->sole(); + $this->assertSame('工厂-河北雅柏代发仓', $row->warehouse_name); + } + + public function test_existing_null_warehouse_rows_are_backfilled_from_outbound_mapping(): void + { + DB::connection('business_mirror')->table('jst_oms_shipping')->insert([ + 'source_id' => 1010416801, + 'sku_source_id' => 4844766, + 'express_no' => 'JDLD13294409324', + 'trade_no' => '3697437005510067', + 'ship_time' => '2026-11-30 13:28:29', + 'qty' => 1, + 'warehouse_name' => null, + ]); + $factory = $this->createMock(UpstreamReadOnlyQueryFactory::class); + $factory->method('forSource')->willReturn($this->createMock(UpstreamReadOnlyQuery::class)); + $sync = new ShippingReplicaSynchronizer($factory); + (new \ReflectionProperty($sync, 'outboundMap'))->setValue($sync, [ + 'byL' => ['JDLD13294409324' => '6505341'], + 'byO' => [], + 'byLO' => ['JDLD13294409324|3697437005510067' => '6505341'], + 'byOAll' => [], + 'ioL' => ['6505341' => 'JDLD13294409324'], + ]); + (new \ReflectionProperty($sync, 'ioWare'))->setValue($sync, ['6505341' => '工厂-河北雅柏代发仓']); + + $method = new \ReflectionMethod($sync, 'backfillMissingWarehouses'); + $updated = $method->invoke($sync, '2026-11-01 00:00:00', '2026-12-01 00:00:00'); + + $this->assertSame(1, $updated); + $this->assertSame( + '工厂-河北雅柏代发仓', + DB::connection('business_mirror')->table('jst_oms_shipping')->where('source_id', 1010416801)->value('warehouse_name'), + ); + } + public function test_stale_express_detail_carrier_and_warehouse_follow_the_actual_outbound(): void { $upstream = $this->createMock(UpstreamReadOnlyQuery::class);