>> */ private array $replacementPackages = []; /** @var array */ private array $replacementHasFreight = []; /** @var array */ private array $replacementHasItems = []; /** @var array> */ private array $replacementSyntheticSkuIds = []; private int $replacementRowCount = 0; private int $packagesProcessed = 0; private int $packagesWithoutItems = 0; private int $packagesRetainedForMissingItems = 0; private int $packagesRetainedForUnmatchedAmount = 0; /** 本轮因商品已更正(新旧条码完全不同)而覆盖旧记录的包裹数;旧金额属于错配商品,不再阻止更新。 */ private int $packagesItemsCorrected = 0; /** 当前正在写入的包裹,商品是否取自出库单实发明细(发货数据视图)。 */ private bool $itemsFromView = false; /** @var array 待替换包裹 => 商品取自出库单实发明细 */ private array $replacementFromView = []; /** 本轮按条码沿用旧金额的明细行数(商品行 ID 变化但条码相同)。 */ private int $amountsMatchedByBarcode = 0; private int $staleMirrorPackages = 0; private int $supersededRemoved = 0; private int $outboundScanned = 0; private int $purchaseScanned = 0; /** @var array */ private array $seenSourceIds = []; /** @var array 发货明细已占用的窗口内订单号 */ private array $expressOrderIds = []; /** @var list */ private array $dwsFailedDays = []; private readonly \Modules\EcommerceFinance\Services\UpstreamReadOnlyQuery $up; /** 副本库查询超时后重试用的长超时连接(120 秒),第一次超时才建 */ private ?\Modules\EcommerceFinance\Services\UpstreamReadOnlyQuery $patient = null; private readonly UpstreamReadOnlyQueryFactory $queries; /** 读到够早就停:窗口开始前多少天(留足预售等「早建单、晚发货」的余量) */ private const EARLY_STOP_DAYS = 120; /** 连续多少页(每页 1500 行)都早于上面的界限才停 */ private const EARLY_STOP_PAGES = 40; /** 本次发货扫描是否因「读到够早」提前结束(进度里显示) */ public bool $earlyStopped = false; /** @var array> 仅缓存需要补齐字段的订单。 */ private array $orderMetadata = []; /** 长超时连接的秒数:按 IN 查订单表在副本库忙时会超过默认 15 秒(2026-11/09 整月同步都死在这里) */ private const PATIENT_TIMEOUT_SECONDS = 120; private readonly \Illuminate\Database\ConnectionInterface $db; /** @var array */ private array $buffer = []; /** @var array 窗口内 dws 销售全量商品缓存 sourceno=>items */ private array $dwsCache = []; /** @var array> 本批 交易单号|快递单号(去@) => [sku => 行数],来自聚水潭运费明细,按包裹记录实发商品 */ private array $fysPackageSkus = []; /** @var array 本批 交易单号 => 运费明细里的快递单号个数(去@),>1 即多包裹订单 */ private array $fysSoTrackCount = []; /** @var array 本轮 express/autoship 已处理(含按标签排除)的出库单 io_id */ private array $doneIo = []; /** @var array 本轮已处理的快递单号(去@) */ private array $doneTrack = []; /** 已实际输出的快递单号(去@),用于判断虚拟/补差单是否借用了别的包裹单号 */ private array $emittedTrack = []; /** @var array 本次已吐出包裹的交易单号 */ private array $emittedSo = []; /** 快递单号 => 交易单号 => 首包来源键;0 表示已经处理,但无法确认所有包裹对应的出库单。 */ private array $doneTrackSo = []; /** @var array 已确认是同一快递单号下不同出库单的包裹。 */ private array $repeatedOutboundSources = []; /** @var array 本轮按规则排除的包裹 source_id(取消/拆分/合并/线上发货),窗口内旧记录需清掉 */ private array $excludedSourceIds = []; /** @var array 最近一次 loadViewItems 的 io_id => 平台(视图 shop_site,工作平台口径) */ private array $ioSite = []; /** @var array 最近一次 loadViewItems 的 io_id => 视图收货省市区(工作平台口径) */ private array $ioAddr = []; /** @var array io_id => 出库时间 io_date(工作平台发货时间口径) */ private array $ioDate = []; /** @var array io_id => 出库单快递公司(工作平台按实际出库单取,发货明细可能停在作废前的旧分配) */ private array $ioLc = []; /** @var array io_id => 出库单线上重量 weight(整单重量,聚水潭销售出库单口径;0 表示出库单没有) */ private array $ioWeight = []; /** @var array io_id => 出库单实称重量 f_weight(只存称过重的) */ private array $ioFWeight = []; /** @var array io_id => 出库单发货仓 wms_co_id */ private array $ioWms = []; /** @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 = []; /** @var array io_id => 是否有效出库单(非作废/取消) */ private array $ioOk = []; /** 换单配对查询超时而跳过的页数(白天副本库繁忙时,不让单页超时中断整轮同步) */ private int $pairingSkipped = 0; /** 工作平台口径:快递名称为"无需物流"(补差/信誉/运费等虚拟发货)的包裹,仓库统一显示自动发货仓 */ private const NO_LOGISTICS = '无需物流'; private const NO_LOGISTICS_WAREHOUSE = '简尚-自动发货仓'; /** @var array 最近一次 loadViewItems 的 io_id => 视图店铺名(发货明细缺店铺时兜底) */ private array $ioShop = []; /** @var array 最近一次 loadViewItems 的 io_id => 视图快递名称 expressName(工作平台显示的快递名称) */ private array $ioExpress = []; /** @var array 最近一次 loadViewItems 的 io_id => 视图发货仓 wareHoursName(工作平台显示的仓库) */ private array $ioWare = []; /** @var array 窗口内出库单映射(见 emptyIoMap) */ private array $outboundMap = ['byL' => [], 'byO' => [], 'byLO' => [], 'byOAll' => [], 'ioL' => []]; public function __construct(UpstreamReadOnlyQueryFactory $factory) { $this->queries = $factory; $this->up = $factory->forSource(self::SOURCE); $this->db = DB::connection((string) config('jushuitan.connection', 'jushuitan_local')); $this->db->disableQueryLog(); } public static function make(): self { return new self(app(UpstreamReadOnlyQueryFactory::class)); } public function sync( ?Carbon $from = null, ?Carbon $to = null, int $limit = 2000, ?callable $progress = null, bool $skipFreight = false, bool $changesOnly = false, ): array { $this->markRunning(); $this->earlyStopped = false; $this->orderMetadata = []; try { $windowed = $from && $to; 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. $this->replaceWindow = (bool) $windowed; $this->packagesProcessed = 0; $this->packagesWithoutItems = 0; $this->packagesRetainedForMissingItems = 0; $this->packagesRetainedForUnmatchedAmount = 0; $this->packagesItemsCorrected = 0; $this->amountsMatchedByBarcode = 0; $this->staleMirrorPackages = 0; $this->shipTimeFixed = 0; $this->weightFixed = 0; $this->placeholderPurged = 0; $this->supersededRemoved = 0; $this->outboundScanned = 0; $this->purchaseScanned = 0; $this->seenSourceIds = []; $this->expressOrderIds = []; $this->dwsFailedDays = []; $now = now(); $fromS = $windowed ? $from->format('Y-m-d H:i:s') : null; $toS = $windowed ? $to->format('Y-m-d H:i:s') : null; $changesFromS = null; if ($changesOnly) { $changesFrom = $to->copy()->subHours(self::CHANGES_LOOKBACK_HOURS); if ($changesFrom->lt($from)) { $changesFrom = $from->copy(); } $changesFromS = $changesFrom->format('Y-m-d H:i:s'); } if ($skipFreight) { $this->markFreightIncomplete($fromS, $toS); } $this->db->table('jst_oms_shipping')->whereIn('source_id', self::DEMO_SOURCE_IDS)->delete(); if ($skipFreight && $progress) { $progress('仅补数量:按包裹分批替换,已有运费/结算重量在事务中保留;不预删日期窗口'); } $total = 0; $auto = 0; $outb = 0; $pout = 0; $this->doneIo = []; $this->doneTrack = []; $this->emittedTrack = []; $this->emittedSo = []; $this->doneTrackSo = []; $this->repeatedOutboundSources = []; $this->excludedSourceIds = []; $this->ioDate = []; $this->ioLc = []; $this->ioWms = []; $this->ioWeight = []; $this->ioFWeight = []; $this->wmsNames = []; $this->warehouseDirectory = []; $this->pendingWarehouse = []; $this->ioOk = []; $this->pairingSkipped = 0; $warehousesBackfilled = 0; $purged = 0; $platformFixed = 0; if ($windowed) { $this->preloadWarehouseDirectory(); if (! $changesOnly) { $this->preloadDws($from, $to); $this->preloadOutboundMap($fromS, $toS); if ($progress) { $progress('dws 预载完成:' . count($this->dwsCache) . ' 个 sourceno'); $progress(sprintf( '出库映射预载完成:%d 个快递单号,%d 个内部单号', count($this->outboundMap['byL']), count($this->outboundMap['byO']), )); } } elseif ($progress) { $progress('增量补变化使用本地共享发货镜像,不预载副本库大表'); } $total = $this->syncExpress(true, $fromS, $toS, $limit, $now, $progress, $changesOnly, $changesFromS); $this->applyPendingWarehouses($progress); gc_collect_cycles(); if ($changesOnly) { // updatedAt 增量只处理共享镜像命中的发货明细;需要副本库大表的仓库回填、 // 自动发货仓、出库/采购兜底和重量校正全部留给夜间完整同步。 $changeFromS = $changesFromS ?? $fromS; $purged = $this->purgeExcludedPackages($changeFromS, $toS); $platformFixed = $this->normalizePlatformCodes($changeFromS, $toS); $this->placeholderPurged = $this->purgeZeroQtyPlaceholders($changeFromS, $toS); $this->staleMirrorPackages = 0; if ($progress) { $progress('增量补变化完成:仅使用共享镜像,副本库兜底与重量校正交由夜间完整同步校准'); } } else { $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) { $progress('平台代码(AS/IMPORT/历史等)按店铺还原:' . $platformFixed . ' 行'); } if ($progress && $purged > 0) { $progress('清除已排除包裹(取消/拆分/合并/线上发货):' . $purged . ' 行'); } $this->staleMirrorPackages = $this->countUnseenMirrorPackages($fromS, $toS); if (! $skipFreight && $this->staleMirrorPackages === 0) { $removed = $this->dedupAtPrefix($fromS, $toS); if ($progress && $removed > 0) { $progress('去除@重复单号:' . $removed . ' 条'); } } try { $this->placeholderPurged = $this->purgeZeroQtyPlaceholders($fromS, $toS); // 出库单校正查副本库,偶发超时:重试几次,仍失败才跳过(并在进度里报出) for ($try = 1; ; $try++) { try { $al = $this->alignWithOutbound($fromS, $toS); break; } catch (Throwable $e) { if ($try >= 3) { throw $e; } if ($progress) { $progress('按销售出库单校正失败,第 ' . $try . ' 次重试:' . mb_substr($e->getMessage(), 0, 120)); } if (! app()->runningUnitTests()) { sleep(30); } } } $this->shipTimeFixed = $al['ship_time']; $this->weightFixed = $al['weight']; if ($progress && ($this->shipTimeFixed > 0 || $this->weightFixed > 0)) { $progress('按销售出库单校正:发货时间 ' . $this->shipTimeFixed . ' 个包裹,线上/实称重量 ' . $this->weightFixed . ' 个包裹'); } if ($progress && $this->placeholderPurged > 0) { $progress('清理订单占位商品行(数量0):' . $this->placeholderPurged . ' 个包裹'); } } catch (Throwable $e) { if ($progress) { $progress('按销售出库单校正(发货时间/线上实称重量)跳过:' . $e->getMessage()); } } // 报价核算运费(报价管理的报价):只核算核算起始日以后的发货数据,失败不影响同步结果 if ($toS > \Modules\EcommerceFinance\Services\Freight\FreightCarrierRules::START_DATE) { try { $fr = app(\Modules\EcommerceFinance\Services\Freight\ShippingFreightService::class)->recalculate($fromS, $toS); if ($progress && $fr['packages'] > 0) { $progress('报价核算运费:' . $fr['packages'] . ' 个包裹,核算成功 ' . $fr['ok'] . ' 个'); } } catch (Throwable $e) { report($e); if ($progress) { $progress('报价核算运费跳过:' . mb_substr($e->getMessage(), 0, 160)); } } } } } else { $total = $this->syncExpress(false, $fromS, $toS, $limit, $now, $progress); $this->applyPendingWarehouses($progress); } if ($windowed && ! $changesOnly && ! $skipFreight && $this->staleMirrorPackages === 0) { $this->markCovered(self::FREIGHT_DATASET_PREFIX, $fromS, $toS); } if ($windowed && ! $changesOnly && ($this->dwsFailedDays !== [] || $this->packagesWithoutItems > 0 || $this->packagesRetainedForUnmatchedAmount > 0)) { $this->markItemsIncomplete($fromS, $toS); } elseif ($windowed && ! $changesOnly && ! $skipFreight && $this->staleMirrorPackages === 0) { $this->markCovered(self::ITEMS_DATASET_PREFIX, $fromS, $toS); } $result = ['processed' => $total, 'autoship' => $auto]; if ($windowed) { $result['outbound'] = $outb; $result['purchase_out'] = $pout; $result['packages'] = $this->packagesProcessed; $result['unique_packages'] = count($this->seenSourceIds); $result['packages_without_items'] = $this->packagesWithoutItems; $result['packages_retained_for_missing_items'] = $this->packagesRetainedForMissingItems; $result['packages_retained_for_unmatched_amount'] = $this->packagesRetainedForUnmatchedAmount; $result['packages_items_corrected'] = $this->packagesItemsCorrected; $result['amounts_matched_by_barcode'] = $this->amountsMatchedByBarcode; $result['dws_failed_days'] = $this->dwsFailedDays; $result['stale_mirror_packages'] = $this->staleMirrorPackages; $result['superseded_packages_removed'] = $this->supersededRemoved; $result['tracking_pairing_skipped_pages'] = $this->pairingSkipped; $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; } if ($this->staleMirrorPackages > 0) { $this->markIncompleteWindow($this->staleMirrorPackages); } else { $this->markSucceeded(); } return $result; } catch (Throwable $e) { $this->markFailed($e->getMessage()); throw $e; } finally { $this->dwsCache = []; $this->orderMetadata = []; $this->outboundMap = ['byL' => [], 'byO' => [], 'byLO' => [], 'byOAll' => [], 'ioL' => []]; $this->replacementPackages = []; $this->replacementHasFreight = []; $this->replacementHasItems = []; $this->replacementSyntheticSkuIds = []; $this->replacementFromView = []; $this->itemsFromView = false; $this->replacementRowCount = 0; $this->skipFreight = false; $this->replaceWindow = false; $this->dwsFailedDays = []; $this->seenSourceIds = []; $this->expressOrderIds = []; $this->repeatedOutboundSources = []; gc_collect_cycles(); } } /** @X 与 X 仅在同一订单、同一发货日去重;提供日期窗口时不使用窗口外记录作匹配;剩余 @ 前缀统一去掉。 */ public function dedupAtPrefix(?string $fromS = null, ?string $toS = null): int { $query = $this->db->table('jst_oms_shipping') ->whereNotNull('express_no')->where('express_no', '!=', ''); if ($fromS !== null && $toS !== null) { $query->where('ship_time', '>=', $fromS)->where('ship_time', '<', $toS); } $clean = []; $prefixed = []; foreach ($query->distinct()->cursor(['source_id', 'trade_no', 'express_no', 'ship_time']) as $row) { $tradeNo = trim((string) $row->trade_no); $expressNo = (string) $row->express_no; $sourceId = (int) $row->source_id; $shipDate = substr((string) $row->ship_time, 0, 10); if ($tradeNo === '' || $sourceId <= 0 || $shipDate === '') { continue; } if ($expressNo[0] === '@') { $prefixed[$sourceId] = [$tradeNo, $shipDate, substr($expressNo, 1)]; } else { $clean[$tradeNo][$shipDate][$expressNo] = true; } } $toDel = []; foreach ($prefixed as $sourceId => [$tradeNo, $shipDate, $expressNo]) { if (! isset($this->repeatedOutboundSources[$sourceId]) && $expressNo !== '' && isset($clean[$tradeNo][$shipDate][$expressNo])) { $toDel[] = $sourceId; } } $removed = 0; foreach (array_chunk($toDel, 500) as $chunk) { $delete = $this->db->table('jst_oms_shipping')->whereIn('source_id', $chunk); if ($fromS !== null && $toS !== null) { $delete->where('ship_time', '>=', $fromS)->where('ship_time', '<', $toS); } $removed += (int) $delete->delete(); } // 剩余 @X:工作平台导出单号不带 @,统一去掉前缀(只处理本次窗口) $strip = $this->db->table('jst_oms_shipping')->where('express_no', 'like', '@%'); if ($fromS !== null && $toS !== null) { $strip->where('ship_time', '>=', $fromS)->where('ship_time', '<', $toS); } $strip->update(['express_no' => $this->db->raw('SUBSTR(express_no, 2)')]); return $removed; } /** 主口径:发货单(dlv 镜像) × 每件商品。 */ private function syncExpress( bool $windowed, ?string $fromS, ?string $toS, int $limit, $now, ?callable $progress = null, bool $changesOnly = false, ?string $changesFromS = null, ): int { $batch = $changesOnly ? 500 : 1500; $maxBatches = $changesOnly ? 200 : $this->maxExpressBatches; $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_status_name, e.order_labels'; // 窗口模式:只按主键 e.id 翻页(有索引,毫秒级),send_time 窗口过滤放到 PHP, // 避免每页都对无索引的 send_time 做全表扫描(那是"卡死"的真凶)。 $fromTs = $fromS !== null ? strtotime($fromS) : null; $toTs = $toS !== null ? strtotime($toS) : null; $total = 0; $scanned = 0; $lastId = null; // 读到够早就停:连续 EARLY_STOP_PAGES 页都没有窗口内的单、且整页最晚发货时间早于窗口开始前 EARLY_STOP_DAYS 天。 // 以前一直读到表头(全部历史),40 天同步每晚都要读几百万行、查几千次订单表,副本库一忙就超时。 $oldPages = 0; $stopBefore = $fromTs !== null ? $fromTs - self::EARLY_STOP_DAYS * 86400 : null; for ($b = 0; $b <= $maxBatches; $b++) { if ($changesOnly) { $rows = $this->loadChangedExpressFromMirror($changesFromS ?? $fromS, $toS, $batch, $lastId); } 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"; } if (! $changesOnly && $oldPages >= self::EARLY_STOP_PAGES) { $this->earlyStopped = true; break; } if (! $changesOnly) { $rows = $this->selectWithReconnect($sql, $bind); } if ($rows === []) { break; } if ($b === $maxBatches) { throw new RuntimeException('发货扫描达到批次上限,仍有未读取的上游数据。'); } $cnt = count($rows); $scanned += $cnt; foreach ($rows as $r) { $lastId = $r['id']; } // 增量模式补齐整页订单字段,并且只读本地镜像;完整同步仍只查缺失字段。 $this->loadOrderMetadataForRows($rows, $changesOnly, $changesOnly); $rows = array_map(fn (array $row): array => $this->mergeOrderMetadata($row), $rows); if ($windowed) { $kept = []; $pageHasUnknownDate = false; foreach ($rows as $r) { $st = ($r['send_time'] ?? null) ?: ($r['jo_send'] ?? null); $ts = ($st !== null && $st !== '') ? strtotime((string) $st) : null; $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; } if ($ts !== null && $ts !== false) { $pageLatest = max($pageLatest ?? $ts, $ts); } else { $pageHasUnknownDate = true; } } $rows = $kept; if (! $pageHasUnknownDate && $stopBefore !== null && $kept === [] && isset($pageLatest) && $pageLatest < $stopBefore) { $oldPages++; } else { $oldPages = 0; } unset($pageLatest); } $oids = []; $soIds = []; $logs = []; foreach ($rows as $r) { $so = (string) ($r['so_id'] ?? ''); if ($so !== '') { $soIds[$so] = true; } $oid = (string) ($r['inner_order_id'] ?? ''); if ($oid !== '') { $oids[$oid] = true; } $lg = (string) ($r['logistic_id'] ?? ''); if ($lg !== '') { $logs[$lg] = true; } } if ($changesOnly) { // 白天增量完全从共享镜像取包裹和订单商品;副本库只留给夜间完整校准。 $ioMap = $this->emptyIoMap(); $swap = []; $viewItems = []; [$byOid, $bySo] = $this->loadMirrorItems(array_keys($oids)); $dws = []; $fysItems = []; $existingItems = $this->loadExistingShippingItems(array_map( static fn (array $row): int => (int) ($row['id'] ?? 0), $rows, )); $skus = $this->loadMirrorSkus($this->collectSkuIds($byOid, $existingItems, $bySo, $dws, $viewItems, $fysItems)); $freight = []; } else { // 主口径:发货数据视图按出库单(io_id)取实发商品 $ioMap = $this->ioMapFor($windowed, array_keys($logs), array_keys($oids)); $swap = $this->pairChangedTracking($rows, $ioMap); $ioIds = []; $fallbackOids = []; $fallbackSoIds = []; foreach ($rows as $r) { $io = isset($swap[(string) ($r['id'] ?? '')]) ? $swap[(string) $r['id']]['io'] : $this->ioFor($ioMap, (string) ($r['logistic_id'] ?? ''), (string) ($r['inner_order_id'] ?? '')); if ($io !== '') { $ioIds[$io] = true; } } $viewItems = $this->loadViewItems(array_keys($ioIds)); // 出库视图已给出实发商品时不再扫描订单商品表;只有找不到出库单的包裹才走订单/运费兜底。 foreach ($rows as $r) { $io = isset($swap[(string) ($r['id'] ?? '')]) ? $swap[(string) $r['id']]['io'] : $this->ioFor($ioMap, (string) ($r['logistic_id'] ?? ''), (string) ($r['inner_order_id'] ?? '')); if ($io !== '' && ! empty($viewItems[$io])) { continue; } $oid = (string) ($r['inner_order_id'] ?? ''); $so = (string) ($r['so_id'] ?? ''); if ($oid !== '') { $fallbackOids[$oid] = true; } if ($so !== '') { $fallbackSoIds[$so] = true; } } [$byOid, $bySo] = $this->loadAllItems(array_keys($fallbackOids), array_keys($fallbackSoIds), ! $windowed); $dws = []; foreach (array_keys($fallbackSoIds) as $mso) { if (empty($bySo[$mso]) && ! empty($this->dwsCache[$mso])) { $dws[$mso] = $this->dwsCache[$mso]; } } $fysItems = $fallbackSoIds === [] ? [] : $this->loadFysPackageSkus(array_keys($fallbackSoIds)); $skus = $this->loadSkus($this->collectSkuIds($byOid, $bySo, $dws, $viewItems, $fysItems)); // 白天补变化不重算运费:运费不是数量来源,且按几百个交易单号回查会拖住整页。 $freight = $this->skipFreight ? [] : $this->loadFreight(array_keys($soIds)); } foreach ($rows as $r) { $pkgId = (int) ($r['id'] ?? 0); if ($pkgId === 0) { continue; } if ($this->excludedOrderStatus($r['order_status_name'] ?? $r['jo_status'] ?? null)) { // 订单已取消/已拆分/已合并:实际发货在子单或合并单上,工作平台不出此行。 // 只登记本行自己的单号,不登记订单单号(可能是子单真实单号,需留给出库单兜底) $this->markDone('', (string) ($r['logistic_id'] ?? '')); $this->markTrackSo((string) ($r['so_id'] ?? ''), 0, (string) ($r['logistic_id'] ?? '')); $this->excludeSource($pkgId); continue; } $sw = $swap[(string) $pkgId] ?? null; if ($sw !== null) { // 换单:快递明细仍是旧单号,出库单已换成新单号 → 用新单号与对应出库单(工作平台口径) $r['logistic_id'] = $sw['l_id']; } $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; // 线上发货(平台代发/云仓):工作平台不拉,对齐排除(发货明细标签可能滞后,订单标签一并判断) } if ($changesOnly && ! empty($existingItems[$pkgId])) { // 包裹主数据变化时沿用页面已有商品行,避免多包裹订单被整单商品覆盖。 $items = $existingItems[$pkgId]; $this->itemsFromView = true; } else { $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($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); $pkg = $this->withIoWeight($io, $this->pkgFromExpress($r, $tracking, $shipTime)); $pkg = $this->withOutboundCarrier($io, $r, $pkg, $pkgId); $pkg = $this->withViewCarrier($io, $pkg, $pkgId); $pkg['platform'] = $this->platformOf($io, $pkg['platform']); $pkg = $this->withViewAddr($io, $pkg); $total += $this->emitPackage($pkgId, $pkg, $items, $skus, $freight, $so, $tracking, $now); } unset($rows, $byOid, $bySo, $dws, $skus, $freight); if ($b % 20 === 0) { gc_collect_cycles(); } if ($progress && $b % 20 === 0) { $progress(sprintf('发货:已扫描 %d 行,命中窗口 %d 件', $scanned, $total)); } if ($cnt < $batch) { break; } if (! $windowed && $total >= $limit) { break; } } if ($progress) { $progress(sprintf('发货完成:扫描 %d 行,处理 %d 件', $scanned, $total) . ($this->earlyStopped ? sprintf('(已读到窗口开始前 %d 天以前,提前结束)', self::EARLY_STOP_DAYS) : '')); } $this->flushPending(); return $total; } /** 按当前页订单键补齐订单字段,并复用已缓存的结果。 */ private function loadOrderMetadataForRows(array $rows, bool $allRows = false, bool $mirrorOnly = false): void { $oids = []; foreach ($rows as $row) { if (! $allRows && trim((string) ($row['send_time'] ?? '')) !== '' && trim((string) ($row['logistic_id'] ?? '')) !== '') { continue; } $oid = (string) ($row['inner_order_id'] ?? ''); if ($oid !== '' && ! array_key_exists($oid, $this->orderMetadata)) { $oids[$oid] = true; } } // 先查本地订单镜像 ops_jst_orders(o_id 有索引,毫秒级):已发货的订单直接用镜像; // 镜像里没有、或镜像里还没发货时间的(镜像每天 05:00 刷新,之后发的单)才去副本库查。 // 副本库按 o_id IN 查 rpt.jst_Orders 很慢,2026-11/09 整月同步都死在这一步。 $pending = $this->loadOrderMetadataFromMirror(array_keys($oids), ! $mirrorOnly); if ($mirrorOnly) { foreach ($oids as $oid => $_) { $this->orderMetadata[$oid] ??= ['l_id' => null, 'send_date' => null, 'status' => null, 'online' => false]; } return; } foreach (array_chunk($pending, 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) { $this->rememberOrderMetadata($row); } foreach ($chunk as $oid) { // 记录无匹配订单,避免后续分页反复查询同一个缺失键。 $this->orderMetadata[$oid] ??= ['l_id' => null, 'send_date' => null, 'status' => null, 'online' => false]; } } } /** 全表扫描会缓存数百万订单:只留判断需要的精简字段(状态仅存会被排除的三种,标签只存是否线上发货)。 */ private function rememberOrderMetadata(array|object $row): void { $row = (array) $row; $oid = (string) ($row['o_id'] ?? ''); if ($oid === '') { return; } $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' => $st !== '' ? $st : null, 'labels' => $row['labels'] ?? null, 'online' => $this->excludedByLabel($row['labels'] ?? null), 'pay_date' => $row['pay_date'] ?? null, 'receiver_state' => $row['receiver_state'] ?? null, 'receiver_city' => $row['receiver_city'] ?? null, 'receiver_district' => $row['receiver_district'] ?? null, 'receiver_address' => $row['receiver_address'] ?? null, 'receiver_name' => $row['receiver_name'] ?? null, 'receiver_mobile' => $row['receiver_mobile'] ?? null, 'receiver_phone' => $row['receiver_phone'] ?? null, 'buyer_message' => $row['buyer_message'] ?? null, 'logistics_company' => $row['logistics_company'] ?? null, 'order_from' => $row['order_from'] ?? null, 'wms_co_id' => $row['wms_co_id'] ?? null, ]; } /** * 本地订单镜像里已发货(有发货时间)的订单直接记下,返回还要去副本库查的订单号。 * 镜像没建好或缺字段时整体退回副本库。 * * @param list $oids * @return list */ private function loadOrderMetadataFromMirror(array $oids, bool $requireSendDate = true): array { if ($oids === [] || ! $this->orderMirrorReady()) { return $oids; } $found = []; try { foreach (array_chunk($oids, 1000) as $chunk) { $keys = array_map(static fn (string $o) => ctype_digit($o) ? (int) $o : $o, $chunk); $rows = $this->orderMirror()->table('ops_jst_orders')->whereIn('o_id', $keys) ->when($requireSendDate, static fn ($query) => $query->whereNotNull('send_date')) ->orderBy('Id') ->get([ 'o_id', 'l_id', 'send_date', 'status', 'labels', 'shop_name', 'pay_date', 'receiver_state', 'receiver_city', 'receiver_district', 'receiver_address', 'receiver_name', 'receiver_mobile', 'receiver_phone', 'buyer_message', 'logistics_company', 'order_from', 'wms_co_id', ]); foreach ($rows as $row) { $this->rememberOrderMetadata($row); $found[(string) $row->o_id] = true; } } } catch (\Throwable $e) { // 镜像查不了不影响同步:剩下的全部走副本库 $this->orderMirrorReady = false; } return array_values(array_filter($oids, static fn (string $o): bool => ! isset($found[$o]))); } private ?bool $orderMirrorReady = null; private function orderMirrorReady(): bool { if ($this->orderMirrorReady === null) { try { $schema = $this->orderMirror()->getSchemaBuilder(); $this->orderMirrorReady = $schema->hasTable('ops_jst_orders') && $schema->hasColumns('ops_jst_orders', ['o_id', 'l_id', 'send_date', 'status', 'labels', 'shop_name']); } catch (\Throwable $e) { $this->orderMirrorReady = false; } } return $this->orderMirrorReady; } private function orderMirror(): \Illuminate\Database\ConnectionInterface { return DB::connection((string) config('upstream_mirrors.connection', 'business_mirror')); } private ?bool $expressMirrorReady = null; private function expressMirrorReady(): bool { if ($this->expressMirrorReady === null) { try { $schema = $this->orderMirror()->getSchemaBuilder(); $this->expressMirrorReady = $schema->hasTable('js_jst_order_express_details') && $schema->hasColumns('js_jst_order_express_details', [ 'id', 'updatedAt', 'inner_order_id', 'so_id', 'logistic_id', 'logistic_company_name', 'send_time', 'shop_name', 'platform_name', 'warehouse_name', 'weight', 'f_weight', ]); } catch (\Throwable $e) { $this->expressMirrorReady = false; } } return $this->expressMirrorReady; } /** 白天增量从共享镜像按 updatedAt 索引读取,避免直连副本库的大视图。 */ private function loadChangedExpressFromMirror(string $fromS, string $toS, int $batch, mixed $lastId): array { if (! $this->expressMirrorReady()) { throw new RuntimeException('发货明细共享镜像尚未建立,增量同步已停止。'); } return $this->orderMirror()->table('js_jst_order_express_details') ->where('updatedAt', '>=', $fromS) ->where('updatedAt', '<', $toS) ->when($lastId !== null, static fn ($query) => $query->where('id', '<', $lastId)) ->orderByDesc('id') ->limit($batch) ->get([ 'id', 'updatedAt', 'so_id', 'inner_order_id', 'logistic_id', 'logistic_company_name', 'send_time', 'shop_name', 'platform_name', 'warehouse_name', 'weight', 'f_weight', ]) ->map(static fn (object $row): array => (array) $row) ->all(); } /** @return array{0:array,1:array} */ private function loadMirrorItems(array $oids): array { $byOid = []; $select = ['o_id', 'raw_so_id', 'sku_id', 'i_id', 'shop_i_id', 'name', 'qty', 'amount', 'send_warehouse', 'Id']; foreach (array_chunk($oids, 800) as $chunk) { if ($chunk === []) { continue; } $keys = array_map(static fn (string $o) => ctype_digit($o) ? (int) $o : $o, $chunk); foreach ($this->orderMirror()->table('ops_jst_order_item')->whereIn('o_id', $keys)->orderBy('Id')->get($select) as $row) { $oid = (string) ($row->o_id ?? ''); if ($oid !== '') { $byOid[$oid][] = $this->itemArr((array) $row); } } } return [$byOid, []]; } /** @return array>> source_id => 页面现有商品行 */ private function loadExistingShippingItems(array $sourceIds): array { $sourceIds = array_values(array_unique(array_filter($sourceIds))); if ($sourceIds === []) { return []; } $out = []; foreach (array_chunk($sourceIds, 800) as $chunk) { $rows = $this->db->table('jst_oms_shipping') ->whereIn('source_id', $chunk) ->orderBy('source_id') ->orderBy('sku_source_id') ->get([ 'source_id', 'sku_source_id', 'item_id', 'barcode', 'product_name', 'qty', 'amount', 'warehouse_name', 'length_cm', 'width_cm', 'height_cm', 'volume_cm3', 'weight_kg', 'supplier_name', ]); foreach ($rows as $row) { $out[(int) $row->source_id][] = [ 'id' => $row->sku_source_id !== null ? (int) $row->sku_source_id : null, 'sku' => $row->barcode, 'iid' => $row->item_id, 'shopid' => null, 'name' => $row->product_name, 'qty' => $row->qty, 'amount' => $row->amount, 'warehouse' => $row->warehouse_name, 'l' => $row->length_cm, 'w' => $row->width_cm, 'h' => $row->height_cm, 'vol' => $row->volume_cm3, 'weight' => $row->weight_kg, 'supplier' => $row->supplier_name, ]; } } return $out; } /** @return array sku_id => 尺寸/重量/供应商 */ private function loadMirrorSkus(array $skuIds): array { $out = []; foreach (array_chunk(array_values(array_unique(array_filter($skuIds))), 800) as $chunk) { if ($chunk === []) { continue; } foreach ($this->orderMirror()->table('ops_jst_sku') ->whereIn('sku_id', $chunk) ->get(['sku_id', 'l', 'w', 'h', 'pack_volume', 'weight', 'supplier_name', 'name', 'i_id']) as $row) { $out[mb_strtolower(trim((string) ($row->sku_id ?? '')))] = [ 'l' => $row->l ?? null, 'w' => $row->w ?? null, 'h' => $row->h ?? null, 'vol' => $row->pack_volume ?? null, 'weight' => $row->weight ?? null, 'supplier' => $row->supplier_name ?? null, 'name' => $row->name ?? null, 'iid' => $row->i_id ?? null, ]; } } return $out; } /** 将订单元数据映射到发货明细,保留测试/兼容来源已提供的字段。 */ private function mergeOrderMetadata(array $row): array { $oid = (string) ($row['inner_order_id'] ?? ''); $metadata = $oid !== '' ? ($this->orderMetadata[$oid] ?? []) : []; $fill = static function (string $key, mixed $value) use (&$row): void { if (($row[$key] ?? null) === null || trim((string) ($row[$key] ?? '')) === '') { $row[$key] = $value; } }; 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'] ?? '') === '') { $row['jo_labels'] = $metadata['labels'] ?? (! empty($metadata['online']) ? '线上发货' : null); } $fill('order_status_name', $metadata['status'] ?? null); $fill('order_labels', $metadata['labels'] ?? null); $fill('pay_time', $metadata['pay_date'] ?? null); $fill('receiver_state', $metadata['receiver_state'] ?? null); $fill('receiver_city', $metadata['receiver_city'] ?? null); $fill('receiver_district', $metadata['receiver_district'] ?? null); $fill('receiver_address', $metadata['receiver_address'] ?? null); $fill('receiver_name', $metadata['receiver_name'] ?? null); $fill('receiver_mobile', $metadata['receiver_mobile'] ?? null); $fill('receiver_phone', $metadata['receiver_phone'] ?? null); $fill('buyer_message', $metadata['buyer_message'] ?? null); $fill('logistic_company_name', $metadata['logistics_company'] ?? null); $fill('dis_co_name', $metadata['logistics_company'] ?? null); $fill('platform_name', $metadata['order_from'] ?? null); $fill('wms_co_id', $metadata['wms_co_id'] ?? null); if (trim((string) ($row['warehouse_name'] ?? '')) === '') { $wms = trim((string) ($row['wms_co_id'] ?? '')); $row['warehouse_name'] = $wms !== '' ? $this->wmsName($wms) : null; } return $row; } /** @return list> */ private function selectWithReconnect(string $sql, array $bindings): array { for ($retry = 0; ; $retry++) { try { // 第一次用默认连接;失败重连后改用长超时连接,避免副本库忙时同一批反复 15 秒超时直到放弃 $query = $retry === 0 ? $this->up : ($this->patient ??= $this->queries->forSourceWithTimeout(self::SOURCE, self::PATIENT_TIMEOUT_SECONDS)); return $query->select($sql, $bindings); } catch (PDOException $e) { if (! $this->isTransientCursorFailure($e) || $retry >= self::UPSTREAM_RECONNECT_RETRIES) { throw $e; } // select() returns only after fetchAll(), so no partial result was consumed. UpstreamConnection::reset(self::SOURCE); if (! app()->runningUnitTests()) { usleep(1000 * (self::UPSTREAM_RECONNECT_BACKOFF_MS[$retry] ?? 30000)); } } } } private function isTransientCursorFailure(PDOException $e): bool { $message = strtolower($e->getMessage()); // 20047 DBPROCESS is dead:副本库查询超时后连接被断开,重连后重查同一批即可 return str_contains($message, 'pdo_dblib: dbnextrow() returned fail') || str_contains($message, 'adaptive server connection timed out [20003]') || str_contains($message, 'dbprocess is dead or not enabled'); } /** 并入自动发货仓:jst_Orders 已发货但不在发货明细表。 */ private function syncAutoShip(string $fromS, string $toS, $now, ?callable $progress = null): int { $batch = 400; $maxBatches = $this->maxAutoShipBatches; $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.wms_co_id'; $total = 0; $lastRid = null; for ($b = 0; $b <= $maxBatches; $b++) { $where = "o.status = 'Sent' AND o.send_date >= ? AND o.send_date < ?"; $bind = [$fromS, $toS]; if ($lastRid !== null) { $where .= ' AND o.Id < ?'; $bind[] = $lastRid; } $sql = "SELECT TOP {$batch} {$cols} FROM rpt.jst_Orders o WHERE {$where} ORDER BY o.Id DESC"; $rows = $this->selectWithReconnect($sql, $bind); if ($rows === []) { break; } if ($b === $maxBatches) { throw new RuntimeException('代发仓扫描达到批次上限,仍有未读取的上游数据。'); } $cnt = count($rows); $eligible = []; foreach ($rows as $r) { $lastRid = $r['rid']; $oid = (string) ($r['o_id'] ?? ''); if ($oid !== '' && ! isset($this->expressOrderIds[$oid])) { $eligible[] = $r; } } $rows = $eligible; $oids = []; $soIds = []; $logs = []; foreach ($rows as $r) { $so = (string) ($r['so_id'] ?? ''); if ($so !== '') { $soIds[$so] = true; } $oid = (string) ($r['o_id'] ?? ''); if ($oid !== '') { $oids[$oid] = true; } $lg = (string) ($r['l_id'] ?? ''); if ($lg !== '') { $logs[$lg] = true; } } [$byOid, $bySo] = $this->loadAllItems(array_keys($oids), array_keys($soIds), false); $dws = []; foreach (array_keys($soIds) as $mso) { if (empty($bySo[$mso]) && ! empty($this->dwsCache[$mso])) { $dws[$mso] = $this->dwsCache[$mso]; } } $ioMap = $this->ioMapFor(true, array_keys($logs), array_keys($oids)); $ioIds = []; foreach ($rows as $r) { $io = $this->ioFor($ioMap, (string) ($r['l_id'] ?? ''), (string) ($r['o_id'] ?? '')); if ($io !== '') { $ioIds[$io] = true; } } $viewItems = $this->loadViewItems(array_keys($ioIds)); $fysItems = $this->loadFysPackageSkus(array_keys($soIds)); $skus = $this->loadSkus($this->collectSkuIds($byOid, $bySo, $dws, $viewItems, $fysItems)); $freight = $this->skipFreight ? [] : $this->loadFreight(array_keys($soIds)); foreach ($rows as $r) { $oid = (string) ($r['o_id'] ?? ''); if ($oid === '') { continue; } // 单号已属于其它包裹(发货明细已出):本单是虚拟/补差单,工作平台此类行快递单号为空 $tracking = $this->tracking((string) ($r['l_id'] ?? ''), '', $freight, (string) ($r['so_id'] ?? '')); if ($tracking !== null && isset($this->emittedTrack[ltrim(trim($tracking), '@')])) { $tracking = null; } $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; // 线上发货:对齐排除 } $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); $total += $this->emitPackage($pkgId, $pkg, $items, $skus, $freight, $so, $tracking, $now, true); } unset($rows, $byOid, $bySo, $dws, $skus, $freight); if ($b % 30 === 0) { gc_collect_cycles(); } if ($cnt < $batch) { break; } } if ($progress) { $progress(sprintf('代发仓完成:处理 %d 件', $total)); } $this->flushPending(); return $total; } /** * 平台统一为工作平台口径:优先取发货数据视图 shop_site;视图没有时把原始平台名映射到工作平台归类名。 */ private function platformOf(string $io, mixed $raw): ?string { if ($io !== '' && isset($this->ioSite[$io])) { return $this->ioSite[$io]; } $raw = trim((string) ($raw ?? '')); if ($raw === '') { return null; } $base = strtoupper(explode(',', $raw)[0]); $map = [ '天猫' => '淘宝天猫', '淘宝' => '淘宝天猫', '京东' => '京东商城', 'MOBILE' => '京东商城', 'PC' => '京东商城', '1688' => '阿里巴巴', '抖音' => '头条放心购', 'TOUTIAOFXG' => '头条放心购', 'PINDUODUO' => '拼多多', 'DEWU' => '得物', '线下' => '线下店铺', ]; return $map[$base] ?? $raw; } /** 订单来源代码(售后补发/导入/历史单等):工作平台显示的是店铺所属平台,不显示代码。 */ private const PLATFORM_CODES = ['AS', '历史AS', 'IMPORT', '历史', 'ERP', 'JDDROPSHIP']; private const PLATFORM_CODE_DIRECT = ['JDDROPSHIP' => '京东厂家直送']; private const SHOP_PREFIX_PLATFORM = [ '京喜' => '京东商城', '京东' => '京东商城', '天猫' => '淘宝天猫', '淘宝' => '淘宝天猫', '拼多多' => '拼多多', '阿里巴巴' => '阿里巴巴', '抖音' => '头条放心购', '得物' => '得物', ]; private static function isPlatformCode(?string $p): bool { $p = trim((string) $p); if ($p === '') { return false; } foreach (explode(',', $p) as $part) { if (! in_array(trim($part), self::PLATFORM_CODES, true)) { return false; } } return true; } /** * 平台为订单来源代码的包裹:按同店铺最常见的平台还原(11 月 53 个对上工作平台 52 个); * JDDROPSHIP 直接为京东厂家直送;店铺无历史时按店铺名前缀;都判断不了则不动。 */ public function normalizePlatformCodes(string $fromS, string $toS): int { $rows = $this->db->table('jst_oms_shipping') ->where('ship_time', '>=', $fromS)->where('ship_time', '<', $toS) ->where(function ($q): void { $q->whereIn('platform', self::PLATFORM_CODES)->orWhere('platform', 'like', '%,%'); }) ->select('platform', 'shop_name')->distinct()->get(); $fixed = 0; $byShop = []; foreach ($rows as $r) { if (! self::isPlatformCode($r->platform)) { continue; } $codes = array_map('trim', explode(',', (string) $r->platform)); $shop = trim((string) $r->shop_name); $target = null; foreach ($codes as $c) { if (isset(self::PLATFORM_CODE_DIRECT[$c])) { $target = self::PLATFORM_CODE_DIRECT[$c]; } } if ($target === null && $shop !== '') { if (! array_key_exists($shop, $byShop)) { $top = $this->db->table('jst_oms_shipping')->where('shop_name', $shop) ->whereNotNull('platform')->where('platform', '!=', '') ->whereNotIn('platform', self::PLATFORM_CODES)->where('platform', 'not like', '%,%') ->groupBy('platform')->orderByRaw('COUNT(*) DESC')->limit(1) ->selectRaw('platform, COUNT(*) AS n')->first(); $byShop[$shop] = $top ? (string) $top->platform : null; } $target = $byShop[$shop]; if ($target === null) { foreach (self::SHOP_PREFIX_PLATFORM as $prefix => $pf) { if (str_starts_with($shop, $prefix)) { $target = $pf; break; } } } } if ($target === null) { continue; } $q = $this->db->table('jst_oms_shipping') ->where('ship_time', '>=', $fromS)->where('ship_time', '<', $toS) ->where('platform', $r->platform); $shop === '' ? $q->where(fn ($w) => $w->whereNull('shop_name')->orWhere('shop_name', '')) : $q->where('shop_name', $r->shop_name); $fixed += $q->update(['platform' => $target]); } return $fixed; } /** 记下按规则排除的包裹;同步结束后清掉它在本窗口里的旧记录(此前版本可能写入过)。 */ private function excludeSource(int $sourceId): void { if ($sourceId > 0) { $this->excludedSourceIds[$sourceId] = true; } } /** * 清除本窗口内"本轮明确排除"的包裹旧记录,并视为已扫描(不计入未见镜像包裹)。 * 只删明确排除的 source_id,未出现在上游扫描里的其它旧记录仍按原逻辑保留待核。 */ private function purgeExcludedPackages(string $fromS, string $toS): int { $this->flushPending(); $ids = []; foreach (array_keys($this->excludedSourceIds) as $id) { if (! isset($this->seenSourceIds[$id])) { $ids[] = $id; $this->seenSourceIds[$id] = true; } } $removed = 0; foreach (array_chunk($ids, 500) as $chunk) { $removed += (int) $this->db->table('jst_oms_shipping')->whereIn('source_id', $chunk) ->where('ship_time', '>=', $fromS)->where('ship_time', '<', $toS)->delete(); } $this->excludedSourceIds = []; return $removed; } /** 登记 单号×交易单号 已处理。 */ private function markTrackSo(string $so, int $sourceId, string $tracking, string ...$aliases): void { $so = trim($so); $trackKey = ltrim(trim($tracking), '@'); foreach ([$tracking, ...$aliases] as $t) { $t = ltrim(trim($t), '@'); if ($t !== '') { $this->doneTrackSo[$t][$so] = $sourceId === 0 || $t !== $trackKey ? 0 : ($this->doneTrackSo[$t][$so] ?? $sourceId); } } } /** 登记已处理的出库单/快递单号,供兜底 pass 防重复。 */ private function markDone(string $io, string ...$tracks): void { if ($io !== '') { $this->doneIo[$io] = true; } foreach ($tracks as $t) { $t = ltrim(trim($t), '@'); if ($t !== '') { $this->doneTrack[$t] = true; } } } /** * 兜底:出库单(按 io_date 窗口)里 express/autoship 都没处理过的包裹,按发货数据视图补吐。 * 典型:工厂代发仓/自有仓出库单无订单行、或同订单其它包裹在发货明细而本包裹不在。 * 防重复按 io_id + 快递单号(去@),不按订单号。 */ private function syncOutbound(string $fromS, string $toS, $now, ?callable $progress = null): int { $mm = $this->selectWithReconnect('SELECT MIN(Id) AS lo, MAX(Id) AS hi FROM ' . self::OUTBOUND . ' WHERE io_date >= ? AND io_date < ?', [$fromS, $toS]); $lo = (int) ($mm[0]['lo'] ?? 0); $hi = (int) ($mm[0]['hi'] ?? 0); if ($lo <= 0 || $hi < $lo) { if ($progress) { $progress('出库单兜底:窗口内无出库单'); } return 0; } $step = max(5000, (int) ceil(($hi - $lo + 1) / 400)); $cols = 'io_id, o_id, so_id, l_id, io_date, pay_date, shop_name, labels, status, logistics_company, weight, f_weight, ' . 'buyer_message, receiver_state, receiver_city, receiver_district, receiver_phone'; $total = 0; $scanned = 0; $emitted = 0; $skip = ['done' => 0, 'notrack' => 0, 'status' => 0, 'label' => 0, 'noitem' => 0]; $virtualEmitted = 0; $seen = []; $page = 0; for ($a = $lo; $a <= $hi; $a += $step) { $page++; $rows = $this->selectOutbound( "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); $this->outboundScanned += count($rows); $pick = []; foreach ($rows as $r) { $io = (string) ($r['io_id'] ?? ''); if ($io === '' || isset($seen[$io])) { continue; } $seen[$io] = true; $this->rememberIoWeight($io, $r); $lid = trim((string) ($r['l_id'] ?? '')); // 无单号出库单一般跳过;但"无需物流"的虚拟发货(信誉/补差/运费等)工作平台收在自动发货仓、快递单号为空,需补吐 $virtual = trim((string) ($r['logistics_company'] ?? '')) === self::NO_LOGISTICS; if ($lid === '' && ! $virtual) { $skip['notrack']++; continue; } if (isset($this->doneIo[$io])) { $skip['done']++; continue; } $st = (string) ($r['status'] ?? ''); if (stripos($st, 'cancel') !== false || stripos($st, 'delete') !== false) { $skip['status']++; continue; } if ($this->excludedByLabel($r['labels'] ?? null)) { $skip['label']++; continue; } $pick[$io] = $r; } if ($pick !== []) { $ioIds = array_map('strval', array_keys($pick)); $viewItems = $this->loadViewItems($ioIds); $heads = $this->loadViewHeads($ioIds); $soIds = []; foreach ($pick as $pio => $r) { $so = $this->outboundSo($r, $heads[(string) $pio] ?? []); if ($so !== '') { $soIds[$so] = true; } } $skus = $this->loadSkus($this->collectSkuIds($viewItems)); $freight = $this->skipFreight ? [] : $this->loadFreight(array_map('strval', array_keys($soIds))); foreach ($pick as $io => $r) { $io = (string) $io; if (empty($viewItems[$io])) { $skip['noitem']++; continue; } $h = $heads[$io] ?? []; $so = $this->outboundSo($r, $h); $tracking = trim((string) ($r['l_id'] ?? '')); $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->withIoWeight($io, $this->pkgFromOutbound($r, $tracking !== '' ? $tracking : null, $this->ts($r['io_date'] ?? null), $h, $so)); $pkg = $this->withViewAddr($io, $pkg); $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; } $virtualEmitted++; } $this->itemsFromView = true; $total += $this->emitPackage($pkgId, $pkg, $viewItems[$io], $skus, $freight, $so, $tracking !== '' ? $tracking : null, $now, true, $sameTrackAgain); $this->markDone($io, $tracking); $this->markTrackSo($so, $pkgId, $tracking); $emitted++; } unset($viewItems, $heads, $skus, $freight); } if ($progress && $page % 40 === 0) { $progress(sprintf('出库单兜底:已扫描 %d 行,补吐 %d 包裹', $scanned, $emitted)); } } $this->flushPending(); if ($progress) { $progress(sprintf( '出库单兜底完成:扫描 %d 行,补吐 %d 包裹 / %d 行(其中无需物流虚拟发货 %d 包裹);跳过 已处理%d 无单号%d 取消删除%d 标签%d 无商品%d', $scanned, $emitted, $total, $virtualEmitted, $skip['done'], $skip['notrack'], $skip['status'], $skip['label'], $skip['noitem'] )); } return $total; } /** * 采购退货出库的商品行:以采购退货明细为准。 * 发货视图对采购退货单会重复出很多行、拼接条码还会被截断,按视图累加会把数量放大(如 93 件变成 1083 件)。 * 明细里有的条码:沿用视图同条码的名称/长宽高等字段,数量取明细;视图没有的条码按明细补一行; * 视图里多出来的条码(截断残码、重复行)丢弃。明细为空时仍按视图。 * * @param list> $viewItems * @param array $poRows 小写条码 => 明细 * @return list> */ private function purchaseOutItems(array $viewItems, array $poRows, ?string $warehouse): array { $byKey = []; foreach ($viewItems as $it) { $k = mb_strtolower(trim((string) ($it['sku'] ?? ''))); if ($k !== '' && ! isset($byKey[$k])) { $byKey[$k] = $it; } } $out = []; foreach ($poRows as $k => $p) { $qty = (int) round((float) ($p['qty'] ?? 0)); if ($qty <= 0) { continue; } $it = $byKey[(string) $k] ?? [ 'id' => null, 'sku' => $p['sku'], 'iid' => null, 'shopid' => null, 'name' => $p['name'] ?? null, 'amount' => null, 'warehouse' => $warehouse, 'l' => null, 'w' => null, 'h' => null, 'vol' => null, 'weight' => null, 'supplier' => null, ]; $it['qty'] = $qty; // A purchase-out correction changes quantity; discard the old view total. unset($it['vol'], $it['mvol'], $it['volume_is_total']); $out[] = $it; } return $out === [] ? $viewItems : $out; } /** * 采购退货出库(退回供应商):工作平台的发货数据视图收录了其中走物流的那部分,按视图补吐。 * 无交易单号/店铺/平台;仓库取视图(发货仓),收货信息取采购退货单。 */ private function syncPurchaseOut(string $fromS, string $toS, $now, ?callable $progress = null): int { $rows = $this->selectWithReconnect( 'SELECT io_id, io_date, status, l_id, so_id, logistics_company, receiver_state, receiver_city, receiver_district, ' . 'receiver_address, receiver_name, receiver_mobile FROM ' . self::PURCHASE_OUT . ' WHERE io_date >= ? AND io_date < ?', [$fromS, $toS] ); $this->purchaseScanned += count($rows); $pick = []; $skip = ['done' => 0, 'cancel' => 0, 'noitem' => 0]; foreach ($rows as $r) { $io = (string) ($r['io_id'] ?? ''); if ($io === '' || isset($pick[$io])) { continue; } $lid = trim((string) ($r['l_id'] ?? '')); if (isset($this->doneIo[$io]) || ($lid !== '' && isset($this->doneTrack[ltrim($lid, '@')]))) { $skip['done']++; continue; } if (stripos((string) ($r['status'] ?? ''), 'cancel') !== false) { $skip['cancel']++; continue; } $pick[$io] = $r; } $total = 0; $emitted = 0; if ($pick !== []) { $ioIds = array_map('strval', array_keys($pick)); $viewItems = $this->loadViewItems($ioIds); // 采购退货:商品明细以采购退货明细(jst_purchaseoutItem)为准,体积=单件长宽高×数量(对齐工作平台) $poItems = []; foreach (array_chunk($ioIds, 800) as $ck) { $ph = implode(',', array_fill(0, count($ck), '?')); foreach ($this->selectWithReconnect("SELECT io_id, sku_id, qty, name FROM rpt.jst_purchaseoutItem WHERE io_id IN ({$ph})", $ck) as $pr) { $sku = trim((string) ($pr['sku_id'] ?? '')); if ($sku === '') { continue; } $pk = mb_strtolower($sku); $pio = (string) $pr['io_id']; if (! isset($poItems[$pio][$pk])) { $name = trim((string) ($pr['name'] ?? '')); $poItems[$pio][$pk] = ['sku' => $sku, 'qty' => 0.0, 'name' => $name !== '' ? $name : null]; } $poItems[$pio][$pk]['qty'] += (float) ($pr['qty'] ?? 0); } } foreach ($poItems as $pio => $prows) { if (! empty($viewItems[$pio])) { $viewItems[$pio] = $this->purchaseOutItems($viewItems[$pio], $prows, $this->ioWare[$pio] ?? null); } } $skus = $this->loadSkus($this->collectSkuIds($viewItems)); foreach ($pick as $io => $r) { $io = (string) $io; if (empty($viewItems[$io])) { $skip['noitem']++; continue; } $lid = trim((string) ($r['l_id'] ?? '')); $tracking = $lid !== '' ? $lid : null; $so = trim((string) ($r['so_id'] ?? '')); $pkg = [ 'tracking' => $tracking, 'so_id' => $so !== '' ? $so : null, 'express_name1' => $r['logistics_company'] ?? null, 'ship_time' => $this->ts($r['io_date'] ?? null), 'pay_time' => null, 'shop_name' => null, 'platform' => $this->ioSite[$io] ?? null, 'dis_co_name' => null, 'warehouse_name' => null, 'r_state' => $r['receiver_state'] ?? null, 'r_city' => $r['receiver_city'] ?? null, 'r_district' => $r['receiver_district'] ?? null, 'r_address' => (string) ($r['receiver_address'] ?? ''), 'r_name' => $r['receiver_name'] ?? null, 'r_mobile' => $r['receiver_mobile'] ?? null, 'r_phone' => null, 'buyer_memo' => null, 'weight' => null, ]; $pkg = $this->withViewAddr($io, $pkg); $this->itemsFromView = true; $total += $this->emitPackage(self::PURCHASE_OUT_OFFSET + (int) $io, $pkg, $viewItems[$io], $skus, [], $so, $tracking, $now, true); $this->markDone($io, (string) $tracking); $emitted++; } } $this->flushPending(); if ($progress) { $progress(sprintf( '采购退货出库完成:窗口 %d 单,补吐 %d 包裹 / %d 行;跳过 已处理%d 已取消%d 视图无商品%d', count($rows), $emitted, $total, $skip['done'], $skip['cancel'], $skip['noitem'] )); } return $total; } /** io_id => 视图表头字段(平台/交易单号/省市区/店铺/快递),出库单表头缺失时兜底用 */ private function loadViewHeads(array $ioIds): array { $out = []; foreach (array_chunk(array_values(array_unique(array_filter($ioIds))), 100) as $chunk) { if ($chunk === []) { continue; } $ph = implode(',', array_fill(0, count($chunk), '?')); $sql = 'SELECT io_id, MAX(shop_site) AS site, MAX(so_id) AS so, MAX(receiver_state) AS st, MAX(receiver_city) AS ci, ' . 'MAX(receiver_district) AS di, MAX(shop_name) AS sn, MAX(expressName) AS ex FROM ' . self::VIEW . " WHERE io_id IN ({$ph}) GROUP BY io_id"; foreach ($this->selectWithReconnect($sql, $chunk) as $r) { $out[(string) $r['io_id']] = $r; } } return $out; } /** 出库单表头 → 包裹级字段 */ private function outboundSo(array $r, array $h): string { $so = trim((string) ($r['so_id'] ?? '')); return $so !== '' ? $so : trim((string) ($h['so'] ?? '')); } private function pkgFromOutbound(array $r, ?string $tracking, ?string $shipTime, array $h, string $so): array { $pick = fn (string $a, string $b) => (($r[$a] ?? null) !== null && trim((string) $r[$a]) !== '') ? $r[$a] : ($h[$b] ?? null); return [ 'tracking' => $tracking, 'so_id' => $so !== '' ? $so : null, 'express_name1' => $pick('logistics_company', 'ex'), 'ship_time' => $shipTime, 'pay_time' => $this->ts($r['pay_date'] ?? null), 'shop_name' => $pick('shop_name', 'sn'), 'platform' => $h['site'] ?? null, 'dis_co_name' => null, 'warehouse_name' => null, 'r_state' => $pick('receiver_state', 'st'), 'r_city' => $pick('receiver_city', 'ci'), 'r_district' => $pick('receiver_district', 'di'), 'r_address' => '', 'r_name' => null, 'r_mobile' => null, 'r_phone' => $r['receiver_phone'] ?? null, 'buyer_memo' => $r['buyer_message'] ?? null, 'weight' => $r['weight'] ?? null, ]; } /** * 输出一个包裹的所有明细行(每件一行;无商品则一行空商品)。 * @return 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); // 信誉单/礼品单等虚拟包裹:只保留虚拟条码(X00002 等),不把订单里的实物商品挂到虚拟单号上。 // 10 月工作平台数据中,含虚拟条码的包裹 730 个,全部只有虚拟条码,无一混装实物。 if (self::isReputationPackage($pkg)) { // 信誉订单仓 / 中通礼品单 / 白云韵达-天猫亿家达:工作平台只记虚拟条码 X00002(10 月 689 行全部如此),不挂订单里的实物商品 $items = [[ 'id' => null, 'sku' => self::REPUTATION_VIRTUAL_BARCODE, 'iid' => null, 'shopid' => null, 'name' => '信誉订单虚拟条码', 'qty' => 1, 'amount' => null, 'warehouse' => null, ]]; } else { $virtualItems = array_values(array_filter($items, fn ($it) => self::isVirtualBarcode($it['sku'] ?? null))); if ($virtualItems !== []) { $items = $virtualItems; } } if ($this->whName($pkg['warehouse_name'] ?? null) === null) { // 包裹级仓库为空:取第一个有效商品行仓库,整包统一(避免同一包裹一行 "0"、一行仓库名) foreach ($items as $it) { $w = $this->whName($it['warehouse'] ?? null); if ($w !== null) { $pkg['warehouse_name'] = $w; break; } } } $n = count($items); $tk = ltrim(trim((string) ($tracking ?? '')), '@'); if ($tk !== '') { $this->emittedTrack[$tk] = true; } if (trim($so) !== '') { $this->emittedSo[trim($so)] = true; } $this->seenSourceIds[$pkgId] = true; $this->packagesProcessed++; if ($n === 0) { $this->packagesWithoutItems++; } // 运费明细的快递单号已去@归一:聚水潭换单/改单后单号常带@前缀,原样拼键会对不上本包裹, // 进而误用同交易单号其它包裹的运费和快递名称。 $f = $freight[$so . '|' . $tk] ?? ($freight[$so . '|'] ?? []); $hasFreight = isset($f['cost']); [$pkg['pkg_online'], $pkg['pkg_actual']] = $this->packageWeights($pkg, $items, $skus); // 聚水潭按「交易单号+单号」返回运费合计。同单号补吐使用本包裹重量,合计只留在首包。 // 已取到上游合计时继续标记运费完整,以免重跑时把旧的重复运费带回来。 if ($sameTrackAgain) { $f = []; } $packageRows = []; if ($n === 0) { $packageRows[] = $this->packageRow($pkgId, $pkgId, $this->buildRow($pkg, [], [], $f, true, '1/1', $now, $auto)); $this->writePackage($pkgId, $packageRows, $hasFreight, false, []); return 1; } $count = 0; $syntheticSkuIds = []; foreach ($items as $idx => $it) { $first = ($idx === 0); $sk = $skus[mb_strtolower(trim((string) ($it['sku'] ?? '')))] ?? []; $skuSid = (int) ($it['id'] ?? ($pkgId * 100 + $idx)); if (($it['id'] ?? null) === null) { $syntheticSkuIds[$skuSid] = true; } $packageRows[] = $this->packageRow($pkgId, $skuSid, $this->buildRow($pkg, $it, $sk, $f, $first, '1/' . $n, $now, $auto)); $count++; } $this->writePackage($pkgId, $packageRows, $hasFreight, true, $syntheticSkuIds); return $count; } /** * 导出明细体积(对齐工作平台 OmsDataDay):默认 数量×长×宽×高; * 特定虚拟快递 → 0;无尺寸 → 空。仓库和承运商不再改变数量倍率。 */ private function detailVolume(mixed $L, mixed $W, mixed $H, float $qty, string $warehouse, string $express): ?float { $cfg = (array) config('jushuitan.detail_volume', []); $express = trim($express); if ($express !== '' && in_array($express, (array) ($cfg['zero_volume_expresses'] ?? []), true)) { return 0.0; } $l = $this->nz($L); $w = $this->nz($W); $h = $this->nz($H); if (! $l || ! $w || ! $h) { return null; } $unit = $l * $w * $h; return round($unit * max($qty, 0), 4); } /** * 商品名称按工作平台口径取商品资料名称(同一条码各店铺一致);商品资料没有名称时才用订单明细名称(京东、得物等是平台标题)。 * 虚拟/补差类明细(信誉订单虚拟条码、补差价等)保留订单明细名称,下游按名称识别。 */ private function productName(mixed $itemName, mixed $skuName): ?string { $item = trim((string) ($itemName ?? '')); $sku = trim((string) ($skuName ?? '')); if ($item !== '' && preg_match('/虚拟条码|透明挂钩|无实物|补差价|差价专用|补收差价/u', $item)) { return (string) $itemName; } return $sku !== '' ? (string) $skuName : ($item !== '' ? (string) $itemName : null); } /** 文本对齐工作平台:工作平台入库时把 & 替换成 ^(如 ">" 导出为 "^gt;",样本 22/22)。 */ private function wpText(mixed $v): ?string { if ($v === null || $v === '') { return $v === '' ? '' : null; } return str_replace('&', '^', (string) $v); } /** 仓库名:聚水潭占位名"{未指定发货仓}"在工作平台仓库表里没有对应,导出为空。 */ private function whName(mixed $w): ?string { $w = trim((string) ($w ?? '')); // 聚水潭部分虚拟/补差单的仓库字段是 "0"(无仓库),工作平台不显示 "0" return ($w === '' || $w === '0' || $w === '{未指定发货仓}') ? null : $w; } /** 组装一件明细行。包裹级字段(实称重量/运费)仅首件携带。 */ private function buildRow(array $pkg, array $it, array $sk, array $f, bool $first, string $countStr, $now, bool $auto): array { $qty = (float) ($it['qty'] ?? 0); $skuW = (float) (($it['weight'] ?? null) ?: ($sk['weight'] ?? 0)); $lineTotal = ! empty($it['weight_is_total']) && ! empty($it['weight']); $onlineW = $skuW > 0 ? round($lineTotal ? $skuW : $skuW * ($qty > 0 ? $qty : 1), 4) : null; $L = ($it['l'] ?? null) ?: ($sk['l'] ?? null); $W = ($it['w'] ?? null) ?: ($sk['w'] ?? null); $H = ($it['h'] ?? null) ?: ($sk['h'] ?? null); $detailVol = $this->detailVolume($L, $W, $H, $qty, (string) ($pkg['warehouse_name'] ?: ($it['warehouse'] ?? '')), (string) ($pkg['express_name1'] ?? '')); // The view carries a parcel total, while a split combo part carries a unit volume. // Keep an explicit total once; multiply unit volumes by the shipped quantity. $vol = isset($it['vol']) ? round((float) $it['vol'] * (($it['volume_is_total'] ?? false) ? 1 : max($qty, 0)), 4) : $detailVol; // 线上重量、实称重量都是整单(包裹)重量,只写在包裹第一行(聚水潭销售出库单口径) $pkgOnline = array_key_exists('pkg_online', $pkg) ? $pkg['pkg_online'] : $onlineW; $pkgActual = array_key_exists('pkg_actual', $pkg) ? $pkg['pkg_actual'] : null; $freightW = (float) ($f['w'] ?? 0); $settleW = $this->skipFreight ? null : ($freightW > 0 ? $freightW : ($pkgActual ?: $pkgOnline)); return $this->cleanPayload([ 'express_no' => $pkg['tracking'], 'trade_no' => $pkg['so_id'], 'item_id' => $it['shopid'] ?? null, 'barcode' => $it['sku'] ?? null, 'product_name' => $this->wpText($this->productName($it['name'] ?? null, $sk['name'] ?? null)), 'qty' => $it['qty'] ?? null, 'pkg_count' => $countStr, 'product_code' => ($it['iid'] ?? null) ?: ($sk['iid'] ?? null), 'express_name1' => $pkg['express_name1'], 'express_name2' => ($f['name'] ?? null) ?: $pkg['express_name1'], 'ship_time' => $pkg['ship_time'], 'pay_time' => $pkg['pay_time'], 'shop_name' => $pkg['shop_name'], 'platform' => $pkg['platform'], 'supplier_name' => ($it['supplier'] ?? null) ?: (($sk['supplier'] ?? null) ?: $pkg['dis_co_name']), 'warehouse_name' => $this->whName($pkg['warehouse_name'] ?: ($it['warehouse'] ?? null)) ?? (trim((string) ($pkg['express_name1'] ?? '')) === self::NO_LOGISTICS ? self::NO_LOGISTICS_WAREHOUSE : null), 'receiver_state' => $pkg['r_state'], 'receiver_city' => $pkg['r_city'], 'receiver_district' => $pkg['r_district'], 'receiver_address' => $pkg['r_address'], 'receiver_name' => $pkg['r_name'], 'receiver_mobile' => $pkg['r_mobile'], 'receiver_phone' => $pkg['r_phone'], 'online_weight' => $first ? $pkgOnline : null, 'actual_weight' => $first ? $pkgActual : null, 'length_cm' => $L, 'width_cm' => $W, 'height_cm' => $H, 'volume_cm3' => $detailVol, 'm_name' => $this->wpText($it['mname'] ?? null), 'm_volume_cm3' => isset($it['mvol']) ? round((float) $it['mvol'], 4) : $vol, 'm_length_cm' => $it['ml'] ?? null, 'm_width_cm' => $it['mw'] ?? null, 'm_height_cm' => $it['mh'] ?? null, 'weight_kg' => $first ? $settleW : null, 'settle_weight_kg' => $first ? $settleW : null, 'amount' => $it['amount'] ?? null, 'freight' => $first ? ($f['cost'] ?? null) : null, 'settle_freight' => $first ? ($f['cost'] ?? null) : null, 'buyer_memo' => $pkg['buyer_memo'], 'modified' => $pkg['ship_time'], 'synced_at' => $now, ]); } /** * 快递公司/仓库以实际出库单为准(工作平台口径):发货明细可能停在作废前的旧分配 * (如先分给工厂代发仓、后改外采由总仓出库;或换单后仍是旧快递公司)。 * 出库单快递公司与发货明细一致时不改,并借此学习 wms_co_id => 仓库名。 */ private function withOutboundCarrier(string $io, array $r, array $pkg, int $pkgId): array { $lc = $io !== '' ? ($this->ioLc[$io] ?? '') : ''; $wms = $io !== '' ? ($this->ioWms[$io] ?? '') : ''; $eLc = trim((string) ($r['logistic_company_name'] ?? '')); $eWh = trim((string) ($r['warehouse_name'] ?? '')); if ($lc !== '' && $lc !== $eLc) { $pkg['express_name1'] = $lc; } if (trim((string) ($pkg['express_name1'] ?? '')) === self::NO_LOGISTICS) { $pkg['warehouse_name'] = self::NO_LOGISTICS_WAREHOUSE; return $pkg; } if ($wms === '') { return $pkg; } // 快递公司一致的明细行用来学习 wms_co_id => 仓库名;仓库统一在扫描结束后按出库单发货仓回填 if ($lc !== '' && $lc === $eLc && $eWh !== '' && $eWh !== '{未指定发货仓}') { $this->wmsNames[$wms][$eWh] = ($this->wmsNames[$wms][$eWh] ?? 0) + 1; } $this->pendingWarehouse[$pkgId] = $wms; return $pkg; } /** * 仓库以发货数据视图的 wareHoursName 为准(工作平台口径);快递名称以出库单/发货明细当前值为准,视图仅兜底。 */ private function withViewCarrier(string $io, array $pkg, int $pkgId): array { if ($io === '') { return $pkg; } // 快递名称以出库单/发货明细的当前值为准:聚水潭换单、改快递公司后出库单与发货明细会更新,工作平台跟着变, // 发货数据视图的 expressName 却停在旧值(如 崔桥顺丰干配→常州德邦)。视图只在出库单/发货明细没有快递名称时兜底。 if (trim((string) ($pkg['express_name1'] ?? '')) === '' && ! empty($this->ioExpress[$io])) { $pkg['express_name1'] = $this->ioExpress[$io]; } if (! empty($this->ioWare[$io])) { $pkg['warehouse_name'] = $this->ioWare[$io]; unset($this->pendingWarehouse[$pkgId]); } return $pkg; } private function wmsName(string $wms): ?string { if (isset($this->warehouseDirectory[$wms])) { return $this->warehouseDirectory[$wms]; } if (empty($this->wmsNames[$wms])) { return null; } $names = $this->wmsNames[$wms]; arsort($names); $top = (int) reset($names); $sum = array_sum($names); // 只在仓库名明确(样本>=3 且占比>=90%)时回填,避免一个发货主体对应多个仓库时误改 if ($top < 3 || $top < 0.9 * $sum) { return null; } 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 { $byName = []; foreach ($this->pendingWarehouse as $pkgId => $wms) { $name = $this->wmsName($wms); if ($name !== null) { $byName[$name][] = $pkgId; } } $n = 0; foreach ($byName as $name => $ids) { foreach (array_chunk($ids, 500) as $chunk) { $n += $this->db->table('jst_oms_shipping')->whereIn('source_id', $chunk) ->where(function ($q): void { $q->whereNull('express_name1')->orWhere('express_name1', '!=', self::NO_LOGISTICS); }) ->where(function ($q) use ($name): void { $q->whereNull('warehouse_name')->orWhere('warehouse_name', '!=', $name); }) ->update(['warehouse_name' => $name]); } } if ($progress && $this->pendingWarehouse !== []) { $progress(sprintf('出库单仓库回填:待补 %d 个包裹,更新 %d 行', count($this->pendingWarehouse), $n)); } $this->pendingWarehouse = []; } /** 出库单行里的整单重量:线上重量 weight、实称重量 f_weight(没称重为 0/空)。 */ private function rememberIoWeight(string $io, array $r): void { if ($io === '' || ! array_key_exists('weight', $r)) { return; } $w = (float) ($r['weight'] ?? 0); $fw = (float) ($r['f_weight'] ?? 0); // 只存标量:窗口同步一次预载几十万张出库单,嵌套数组内存约是标量的十倍 $this->ioWeight[$io] = $w > 0 ? round($w, 4) : 0.0; if ($fw > 0) { $this->ioFWeight[$io] = round($fw, 4); } else { unset($this->ioFWeight[$io]); } } /** 包裹对应的出库单有重量时,带上整单线上/实称重量。 */ private function withIoWeight(string $io, array $pkg): array { if ($io !== '' && isset($this->ioWeight[$io])) { $pkg['io_weight'] = $this->ioWeight[$io] > 0 ? $this->ioWeight[$io] : null; $pkg['io_fweight'] = $this->ioFWeight[$io] ?? null; $pkg['has_io_weight'] = true; } return $pkg; } /** * 包裹整单重量 [线上重量, 实称重量]: * - 有出库单:线上 = 出库单 weight,实称 = 出库单 f_weight(没称重为空,不拿预估重量冒充实称); * - 没有出库单:线上 = 各商品单重×数量之和(没有单重时用发货明细重量),实称 = 发货明细 f_weight。 * * @return array{0:?float,1:?float} */ private function packageWeights(array $pkg, array $items, array $skus): array { if (! empty($pkg['has_io_weight'])) { return [$pkg['io_weight'] ?? null, $pkg['io_fweight'] ?? null]; } $sum = 0.0; foreach ($items as $it) { $sk = $skus[mb_strtolower(trim((string) ($it['sku'] ?? '')))] ?? []; $total = ! empty($it['weight_is_total']) && ! empty($it['weight']); $w = (float) (($it['weight'] ?? null) ?: ($sk['weight'] ?? 0)); $qty = (float) ($it['qty'] ?? 0); $sum += $w > 0 ? ($total ? $w : $w * ($qty > 0 ? $qty : 1)) : 0; } $pkgW = (float) ($pkg['weight'] ?? 0); $fw = (float) ($pkg['f_weight'] ?? 0); return [$sum > 0 ? round($sum, 4) : ($pkgW > 0 ? round($pkgW, 4) : null), $fw > 0 ? round($fw, 4) : null]; } /** 查出库单:副本库没有 weight/f_weight 列时退回不带重量的查询(不影响其它字段)。 */ private function selectOutbound(string $sql, array $bindings): array { try { $rows = $this->selectWithReconnect($sql, $bindings); } catch (Throwable $e) { if (! $this->isMissingColumnError($e) || ! str_contains($sql, 'f_weight')) { throw $e; } $rows = $this->selectWithReconnect(str_replace(['f_weight, ', ', f_weight'], ['', ''], $sql), $bindings); } return app(ShippingWeightPrecision::class)->outboundRows($rows); } /** 发货明细表行 → 包裹级字段(省市区从地址拆) */ private function pkgFromExpress(array $r, ?string $tracking, ?string $shipTime): array { $addr = (string) ($r['receiver_address'] ?? ''); $parts = $addr !== '' ? array_values(array_filter(explode('-', $addr))) : []; return [ 'tracking' => $tracking, 'so_id' => $r['so_id'] ?? null, 'express_name1' => $r['logistic_company_name'] ?? null, 'ship_time' => $shipTime, 'pay_time' => $this->ts($r['pay_time'] ?? null), 'shop_name' => $r['shop_name'] ?? null, 'platform' => $r['platform_name'] ?? null, 'dis_co_name' => $r['dis_co_name'] ?? null, 'warehouse_name' => $r['warehouse_name'] ?? null, 'r_state' => $r['receiver_state'] ?? ($parts[0] ?? null), 'r_city' => $r['receiver_city'] ?? ($parts[1] ?? null), 'r_district' => $r['receiver_district'] ?? ($parts[2] ?? null), 'r_address' => $addr, 'r_name' => $r['receiver_name'] ?? null, 'r_mobile' => $r['receiver_mobile'] ?? null, 'r_phone' => $r['receiver_phone'] ?? null, 'buyer_memo' => $r['buyer_message'] ?? null, 'weight' => $r['weight'] ?? null, 'f_weight' => $r['f_weight'] ?? null, ]; } /** jst_Orders 行(自动发货仓) → 包裹级字段 */ private function pkgFromOrder(array $r, ?string $tracking, ?string $shipTime): array { return [ 'tracking' => $tracking, 'so_id' => $r['so_id'] ?? null, 'express_name1' => $r['logistics_company'] ?? null, 'ship_time' => $shipTime, 'pay_time' => $this->ts($r['pay_date'] ?? null), 'shop_name' => $r['shop_name'] ?? null, '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, 'r_address' => $r['receiver_address'] ?? '', 'r_name' => $r['receiver_name'] ?? null, 'r_mobile' => $r['receiver_mobile'] ?? null, 'r_phone' => $r['receiver_phone'] ?? null, 'buyer_memo' => $r['buyer_message'] ?? null, 'weight' => $r['weight'] ?? null, ]; } private function tracking(string $logisticId, string $joLid, array $freight, string $so): ?string { if ($logisticId !== '') { return $logisticId; } if ($joLid !== '') { return $joLid; } $f = $freight[$so . '|'] ?? []; $no = (string) ($f['no'] ?? ''); return $no !== '' ? $no : null; } /** @return array{0:array,1:array} [byOid, bySo] */ private function loadAllItems(array $oids, array $soIds, bool $loadBySoId = true): array { $byOid = []; $bySo = []; $sel = 'o_id, raw_so_id, sku_id, i_id, shop_i_id, name, qty, amount, send_warehouse, Id'; foreach (array_chunk($oids, 800) as $chunk) { if ($chunk === []) { continue; } $ph = implode(',', array_fill(0, count($chunk), '?')); foreach ($this->selectWithReconnect("SELECT {$sel} FROM rpt.jst_OrderItem WHERE o_id IN ({$ph}) ORDER BY Id", $chunk) as $r) { $k = (string) ($r['o_id'] ?? ''); if ($k !== '') { $byOid[$k][] = $this->itemArr($r); } } } // raw_so_id lacks a usable index in the production replica. Windowed sync already // preloads DWS rows by sourceno, so querying this fallback can turn every batch into // a full-table scan and exceed the upstream timeout. Keep it only for the small, // non-windowed diagnostic mode where DWS is not preloaded. if ($loadBySoId) { foreach (array_chunk($soIds, 800) as $chunk) { if ($chunk === []) { continue; } $ph = implode(',', array_fill(0, count($chunk), '?')); foreach ($this->selectWithReconnect("SELECT {$sel} FROM rpt.jst_OrderItem WHERE raw_so_id IN ({$ph}) ORDER BY Id", $chunk) as $r) { $k = (string) ($r['raw_so_id'] ?? ''); if ($k !== '') { $bySo[$k][] = $this->itemArr($r); } } } } return [$byOid, $bySo]; } /** 开跑前按天预加载窗口内 dws 销售全量到内存,避免逐批扫表。 */ private function preloadDws(\Illuminate\Support\Carbon $from, \Illuminate\Support\Carbon $to): void { $this->dwsCache = []; $seen = []; $day = $from->copy()->subDay()->startOfDay(); $end = $to->copy(); while ($day < $end) { $d = $day->format('Y-m-d'); $day = $day->addDay(); try { $rows = $this->selectWithReconnect("SELECT sourceno, item_id, skuoid, goods_count, sales_amount FROM rpt.dws_sn_sales_full_info_di WHERE stat_date = ?", [$d]); } catch (Throwable) { $this->dwsFailedDays[] = $d; continue; } foreach ($rows as $r) { $so = (string) ($r['sourceno'] ?? ''); $bc = (string) ($r['skuoid'] ?? ''); if ($so === '' || $bc === '') { continue; } $k = $so.'|'.$bc; if (isset($seen[$k])) { continue; } $seen[$k] = true; $this->dwsCache[$so][] = [ 'id' => null, 'sku' => $bc, 'iid' => null, 'shopid' => $r['item_id'] ?? null, 'name' => null, 'qty' => $r['goods_count'] ?? null, 'amount' => $r['sales_amount'] ?? null, 'warehouse' => null, ]; } unset($rows); } } /** jst_OrderItem 缺失时的兜底:dws 销售全量按 sourceno 取商品(条码/商品ID/数量/金额)。 */ private function loadDwsItems(array $soIds): array { $out = []; $seen = []; foreach (array_chunk($soIds, 500) as $chunk) { if ($chunk === []) { continue; } $ph = implode(',', array_fill(0, count($chunk), '?')); $sql = "SELECT sourceno, item_id, skuoid, goods_count, sales_amount FROM rpt.dws_sn_sales_full_info_di WHERE sourceno IN ({$ph})"; foreach ($this->selectWithReconnect($sql, $chunk) as $r) { $so = (string) ($r['sourceno'] ?? ''); $barcode = (string) ($r['skuoid'] ?? ''); if ($so === '' || $barcode === '') { continue; } $k = $so.'|'.$barcode; if (isset($seen[$k])) { continue; } $seen[$k] = true; $out[$so][] = [ 'id' => null, 'sku' => $barcode, 'iid' => null, 'shopid' => $r['item_id'] ?? null, 'name' => null, 'qty' => $r['goods_count'] ?? null, 'amount' => $r['sales_amount'] ?? null, 'warehouse' => null, ]; } } return $out; } private function itemArr(array $r): array { return [ 'id' => $r['Id'] ?? null, 'sku' => $r['sku_id'] ?? null, 'iid' => $r['i_id'] ?? null, 'shopid' => $r['shop_i_id'] ?? null, 'name' => $r['name'] ?? null, 'qty' => $r['qty'] ?? null, 'amount' => $r['amount'] ?? null, 'warehouse' => $r['send_warehouse'] ?? null, ]; } /** * 包裹实发商品: * 1. 出库单实发商品(发货数据视图); * 2. 聚水潭运费明细里本快递单号的商品; * 3. 没有出库单且没有多包裹证据时,才使用内部订单/交易单号商品。 * * 运费明细(fys_jstFreightCostDetail)按 交易单号+快递单号 记录每个包裹的 sku。工厂代发仓等找不到出库单的包裹, * 内部订单/交易单号商品是整单口径,多包裹时会把同订单其它包裹的商品挂到本单号上 * (例:交易单号 3317080548271028274 的韵达包裹被挂成圆通包裹的 DNZ0254102N1217V01; * 交易单号 3316455123356017092 的韵达包裹被挂成 34095J + 雅柏仓的 CZ000935N1201V01)。 */ private function packageItems(string $io, array $viewItems, array $byOid, array $bySo, array $dws, string $oid, string $so, string $tracking): array { $this->itemsFromView = false; if ($io !== '' && ! empty($viewItems[$io])) { $this->itemsFromView = true; return $viewItems[$io]; } $tk = ltrim(trim($tracking), '@'); $packageSkus = ($so !== '' && $tk !== '') ? ($this->fysPackageSkus[$so . '|' . $tk] ?? []) : []; $multiPackage = ($this->fysSoTrackCount[$so] ?? 0) > 1; if ($packageSkus === []) { // An identified outbound package without item detail must remain incomplete. // Whole-order lines may describe a different parcel or the original full item. if ($io !== '' || $multiPackage) { return []; } return $this->itemsFor($byOid, $bySo, $dws, $oid, $so); } // 商品名称、商品ID、数量、金额尽量沿用订单商品;订单里找不到的 sku 按运费明细行数记数量 $pool = []; foreach ([$byOid[$oid] ?? [], $bySo[$so] ?? [], $dws[$so] ?? []] as $list) { foreach ($list as $it) { $key = mb_strtolower(trim((string) ($it['sku'] ?? ''))); if ($key !== '' && ! isset($pool[$key])) { $pool[$key] = $it; } } } $items = []; foreach ($packageSkus as $sku => $rows) { $items[] = $pool[mb_strtolower((string) $sku)] ?? [ 'id' => null, 'sku' => (string) $sku, 'iid' => null, 'shopid' => null, 'name' => null, 'qty' => $rows, 'amount' => null, 'warehouse' => null, ]; } return $items; } private const REPUTATION_VIRTUAL_BARCODE = 'X00002'; private const REPUTATION_WAREHOUSES = ['简尚-信誉订单仓']; private const REPUTATION_CARRIERS = ['中通礼品单', '白云韵达-天猫亿家达']; /** 信誉订单/礼品单虚拟包裹:按仓库或快递判断(系统数据里没有 X00002,X00002 是工作平台导出时补的)。 */ private static function isReputationPackage(array $pkg): bool { return in_array(trim((string) ($pkg['warehouse_name'] ?? '')), self::REPUTATION_WAREHOUSES, true) || in_array(trim((string) ($pkg['express_name1'] ?? '')), self::REPUTATION_CARRIERS, true); } /** 信誉单/礼品单虚拟条码,如 X00002、X00006。 */ private static function isVirtualBarcode(mixed $sku): bool { return preg_match('/^X\\d{5}$/i', trim((string) $sku)) === 1; } /** * 只读诊断:一个快递单号在各上游表里的记录,用于排查发货数据商品为空/错配。 * 不写任何表。 * * @return array */ public function diagnosePackage(string $tracking): array { $t = ltrim(trim($tracking), '@'); $alts = [$t, '@' . $t]; $in = static fn (array $values): string => implode(',', array_fill(0, count($values), '?')); $col = static function (array $rows, string $key): array { $out = []; foreach ($rows as $row) { $value = trim((string) ($row[$key] ?? '')); if ($value !== '') { $out[$value] = true; } } return array_keys($out); }; $out = ['tracking' => $t]; $out['outbound'] = $this->selectWithReconnect( 'SELECT io_id, o_id, so_id, l_id, io_date, status, logistics_company, wms_co_id FROM ' . self::OUTBOUND . ' WHERE l_id IN (?, ?)', $alts ); $ioIds = $col($out['outbound'], 'io_id'); $out['view'] = $ioIds === [] ? [] : $this->selectWithReconnect( 'SELECT io_id, so_id, sku_ids, qty, type, wareHoursName, expressName FROM ' . self::VIEW . " WHERE io_id IN ({$in($ioIds)})", $ioIds ); $out['express_details'] = $this->selectWithReconnect( 'SELECT id, so_id, inner_order_id, logistic_id, logistic_company_name, warehouse_name, send_time FROM rpt.jst_order_express_details WHERE logistic_id IN (?, ?)', $alts ); $out['orders'] = $this->selectWithReconnect( 'SELECT o_id, so_id, l_id, status, logistics_company, send_date, labels FROM rpt.jst_Orders WHERE l_id IN (?, ?)', $alts ); $oids = array_values(array_unique(array_merge( $col($out['outbound'], 'o_id'), $col($out['express_details'], 'inner_order_id'), $col($out['orders'], 'o_id') ))); $out['order_items'] = $oids === [] ? [] : $this->selectWithReconnect( "SELECT o_id, sku_id, qty, name FROM rpt.jst_OrderItem WHERE o_id IN ({$in($oids)})", $oids ); $soIds = array_values(array_unique(array_merge( $col($out['outbound'], 'so_id'), $col($out['express_details'], 'so_id'), $col($out['orders'], 'so_id'), $col($out['view'], 'so_id') ))); $out['freight_detail'] = $soIds === [] ? [] : $this->selectWithReconnect( "SELECT so_id, expressNo, io_id, sku_id, freightCost, weight, expressName FROM rpt.fys_jstFreightCostDetail WHERE so_id IN ({$in($soIds)})", $soIds ); return $out; } /** 该包裹的商品:优先 o_id 精确,取不到回落 so_id。 */ private function itemsFor(array $byOid, array $bySo, array $dws, string $oid, string $so): array { if ($oid !== '' && ! empty($byOid[$oid])) { return $byOid[$oid]; } if ($so !== '' && ! empty($bySo[$so])) { return $bySo[$so]; } if ($so !== '' && ! empty($dws[$so])) { return $dws[$so]; // jst_OrderItem 取不到时,用 dws 销售全量兜底 } return []; } /** 窗口同步按 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 < ?'; $this->outboundMap = $this->mapOutboundRows($this->selectOutbound($sql, [$fromS, $toS])); } /** 出库单行 -> 映射(单号/订单/单号+订单 三种定位,作废重出按有效优先、io_date 最新择优)。 */ private function mapOutboundRows(array $rows): array { $map = $this->emptyIoMap(); foreach ($rows as $r) { $this->addIoRow($map, $r, true, true); } unset($map['rank']); return $map; } private function ioMapFor(bool $windowed, array $logisticIds, array $oIds): array { return $windowed ? $this->outboundMap : $this->loadIoMap($logisticIds, $oIds); } /** * 出库单映射:byL 单号->io、byO 订单->io、byLO 单号|订单->io、byOAll 订单->[io=>单号](仅有效单)、ioL io->单号。 * 同一单号/订单可能有多张出库单(作废重出):优先有效(非 Delete/Cancelled),再取最新 io_date。 */ private function emptyIoMap(): array { return ['byL' => [], 'byO' => [], 'byLO' => [], 'byOAll' => [], 'ioL' => [], 'rank' => ['L' => [], 'O' => [], 'LO' => []]]; } private function addIoRow(array &$m, array $r, bool $indexByL, bool $indexByO): void { $rio = (string) ($r['io_id'] ?? ''); if ($rio === '') { return; } if (! empty($r['io_date'])) { $this->ioDate[$rio] = (string) $r['io_date']; } $lc = trim((string) ($r['logistics_company'] ?? '')); if ($lc !== '') { $this->ioLc[$rio] = $lc; } $wms = trim((string) ($r['wms_co_id'] ?? '')); if ($wms !== '' && $wms !== '0') { $this->ioWms[$rio] = $wms; } $this->rememberIoWeight($rio, $r); $l = ltrim(trim((string) ($r['l_id'] ?? '')), '@'); $o = (string) ($r['o_id'] ?? ''); $m['ioL'][$rio] = $l; $st = strtolower(trim((string) ($r['status'] ?? ''))); $ok = ! in_array($st, ['delete', 'deleted', 'cancelled', 'cancel', 'canceled'], true); $this->ioOk[$rio] = $ok; $rk = ($ok ? '1' : '0') . '|' . (string) ($r['io_date'] ?? '') . '|' . str_pad($rio, 12, '0', STR_PAD_LEFT); if ($indexByL && $l !== '' && (! isset($m['rank']['L'][$l]) || strcmp($rk, $m['rank']['L'][$l]) > 0)) { $m['byL'][$l] = $rio; $m['rank']['L'][$l] = $rk; } // 同一单号多订单共用(拼单/合包):按 单号+订单 精确定位,避免拿到别的订单的商品 $lo = $l . '|' . $o; if ($indexByL && $l !== '' && $o !== '' && (! isset($m['rank']['LO'][$lo]) || strcmp($rk, $m['rank']['LO'][$lo]) > 0)) { $m['byLO'][$lo] = $rio; $m['rank']['LO'][$lo] = $rk; } if ($indexByO && $o !== '') { if ($ok) { $m['byOAll'][$o][$rio] = $l; } if (! isset($m['rank']['O'][$o]) || strcmp($rk, $m['rank']['O'][$o]) > 0) { $m['byO'][$o] = $rio; $m['rank']['O'][$o] = $rk; } } } /** 快递单号/内部单号 -> 出库单 io_id(非窗口诊断模式按需查询;窗口模式用预载映射)。 */ private function loadIoMap(array $logisticIds, array $oIds): array { $map = $this->emptyIoMap(); foreach (array_chunk(array_values(array_unique(array_filter($logisticIds))), 800) as $chunk) { if ($chunk === []) { continue; } $q = []; foreach ($chunk as $c) { $c = ltrim(trim((string) $c), '@'); if ($c !== '') { $q[$c] = true; $q['@' . $c] = true; } } $q = array_keys($q); $ph = implode(',', array_fill(0, count($q), '?')); foreach ($this->selectOutbound('SELECT l_id, io_id, io_date, status, o_id, logistics_company, wms_co_id, weight, f_weight FROM ' . self::OUTBOUND . " WHERE l_id IN ({$ph})", $q) as $r) { $this->addIoRow($map, $r, true, false); } } foreach (array_chunk(array_values(array_unique(array_filter($oIds))), 800) as $chunk) { if ($chunk === []) { continue; } $ph = implode(',', array_fill(0, count($chunk), '?')); foreach ($this->selectOutbound('SELECT o_id, io_id, io_date, l_id, status, logistics_company, wms_co_id, weight, f_weight FROM ' . self::OUTBOUND . " WHERE o_id IN ({$ph})", $chunk) as $r) { $this->addIoRow($map, $r, false, true); } } unset($map['rank']); return $map; } /** * 换单配对:快递明细的单号在出库单里找不到时,到同一内部订单下找一张 * "出库单有单号、但该单号不在任何快递明细里"的出库单,一对一配对(工作平台换单后只保留新单号)。 * * @return array 以快递明细 id 为键 */ private function pairChangedTracking(array $rows, array $ioMap): array { $cands = []; $need = []; foreach ($rows as $r) { $lg = ltrim(trim((string) ($r['logistic_id'] ?? '')), '@'); $oid = (string) ($r['inner_order_id'] ?? ''); $byL = $ioMap['byL'][$lg] ?? null; // 快递明细单号只对应作废出库单时,视为已换单(工作平台显示有效出库单的新单号) $hasValidIo = $byL !== null && ($this->ioOk[(string) $byL] ?? true); if ($lg === '' || $oid === '' || $hasValidIo || empty($ioMap['byOAll'][$oid]) || $this->excludedOrderStatus($r['order_status_name'] ?? $r['jo_status'] ?? null)) { continue; } $need[] = $r; foreach ($ioMap['byOAll'][$oid] as $io => $l) { if ($l !== '' && ! isset($this->doneIo[(string) $io]) && ! isset($this->doneTrack[$l])) { $cands[$l] = true; } } } if ($need === [] || $cands === []) { return []; } // 候选新单号若本身出现在快递明细里(同订单拆包),不能拿来配对 $inExpress = []; foreach (array_chunk(array_keys($cands), 400) as $chunk) { $q = []; foreach ($chunk as $c) { $q[] = (string) $c; $q[] = '@' . $c; } $ph = implode(',', array_fill(0, count($q), '?')); try { $found = $this->selectWithReconnect("SELECT DISTINCT logistic_id FROM rpt.jst_order_express_details WHERE logistic_id IN ({$ph})", $q); } catch (PDOException $e) { if (! $this->isTransientCursorFailure($e)) { throw $e; } // logistic_id 无索引,副本库繁忙时会超时:本页跳过换单配对(保留原单号),不中断整轮 $this->pairingSkipped++; return []; } foreach ($found as $x) { $inExpress[ltrim(trim((string) ($x['logistic_id'] ?? '')), '@')] = true; } } $used = []; $swap = []; foreach ($need as $r) { $oid = (string) $r['inner_order_id']; $ios = $ioMap['byOAll'][$oid]; ksort($ios, SORT_STRING); foreach ($ios as $io => $l) { $io = (string) $io; if ($l === '' || isset($inExpress[$l]) || isset($used[$io]) || isset($this->doneIo[$io]) || isset($this->doneTrack[$l])) { continue; } $used[$io] = true; $swap[(string) $r['id']] = ['io' => $io, 'l_id' => $l, 'old' => (string) $r['logistic_id']]; break; } } return $swap; } private function ioFor(array $ioMap, string $logisticId, string $oid): string { $logisticId = ltrim(trim($logisticId), '@'); if ($logisticId !== '' && $oid !== '' && ! empty($ioMap['byLO'][$logisticId . '|' . $oid])) { return (string) $ioMap['byLO'][$logisticId . '|' . $oid]; } if ($logisticId !== '' && ! empty($ioMap['byL'][$logisticId])) { return (string) $ioMap['byL'][$logisticId]; } if ($logisticId !== '') { return ''; // A different parcel on the same order is not a match. } if ($oid !== '' && ! empty($ioMap['byO'][$oid])) { return (string) $ioMap['byO'][$oid]; } return ''; } /** * io_id -> 实发商品[itemArr](发货数据视图)。 * 单条码行:按(io_id,条码)去重,type=0 之和优先。 * 多条码行(组合件):见 appendComboParts,对齐工作平台导出明细的拆件口径。 */ private function loadViewItems(array $ioIds): array { $agg = []; $multi = []; $this->ioSite = []; $this->ioAddr = []; $this->ioShop = []; $this->ioExpress = []; $this->ioWare = []; // 发货数据视图是计算视图,IN 列表过长时副本库容易超时(11 月起 300 个一批常被断开):按 100 个出库单一批 foreach (array_chunk(array_values(array_unique(array_filter($ioIds))), 100) as $chunk) { if ($chunk === []) { continue; } $ph = implode(',', array_fill(0, count($chunk), '?')); $sql = 'SELECT io_id, sku_ids, qty, type, sku_name, shop_i_id, wareHoursName, expressName, l, w, h, volume, weight, supplier_name, shop_site, shop_name, receiver_state, receiver_city, receiver_district FROM ' . self::VIEW . " WHERE io_id IN ({$ph})"; foreach ($this->selectWithReconnect($sql, $chunk) as $r) { $io = (string) ($r['io_id'] ?? ''); if ($io !== '' && ! isset($this->ioSite[$io]) && trim((string) ($r['shop_site'] ?? '')) !== '') { $this->ioSite[$io] = trim((string) $r['shop_site']); } if ($io !== '' && ! isset($this->ioShop[$io]) && trim((string) ($r['shop_name'] ?? '')) !== '') { $this->ioShop[$io] = trim((string) $r['shop_name']); } if ($io !== '' && ! isset($this->ioExpress[$io]) && trim((string) ($r['expressName'] ?? '')) !== '') { $this->ioExpress[$io] = trim((string) $r['expressName']); } if ($io !== '' && ! isset($this->ioWare[$io]) && trim((string) ($r['wareHoursName'] ?? '')) !== '') { $this->ioWare[$io] = trim((string) $r['wareHoursName']); } if ($io !== '') { foreach (['st' => 'receiver_state', 'ci' => 'receiver_city', 'di' => 'receiver_district'] as $ak => $ac) { $av = trim((string) ($r[$ac] ?? '')); if ($av !== '' && ! isset($this->ioAddr[$io][$ak])) { $this->ioAddr[$io][$ak] = $av; } } } $skuIds = (string) ($r['sku_ids'] ?? ''); if ($io === '' || $skuIds === '') { continue; } // 一行可能逗号拼接多个条码 —— 对齐工作平台导出明细:拆成每条码一件; // 数量与体积按条码数均摊,保证合并求和后与整行值一致(工作平台合并体积"整箱算一次")。 $bcs = array_values(array_filter(array_map('trim', explode(',', $skuIds)), fn ($x) => $x !== '')); if ($bcs === []) { continue; } $n = count($bcs); if ($n > 1) { $multi[$io][] = [ 't' => (string) ($r['type'] ?? ''), 'qty' => (float) ($r['qty'] ?? 0), 'bcs' => $bcs, 'name' => $r['sku_name'] ?? null, 'l' => $r['l'] ?? null, 'w' => $r['w'] ?? null, 'h' => $r['h'] ?? null, 'vol' => $r['volume'] ?? null, 'shopid' => $r['shop_i_id'] ?? null, 'wh' => $r['wareHoursName'] ?? null, 'supplier' => $r['supplier_name'] ?? null, ]; continue; } $isT0 = ((string) ($r['type'] ?? '') === '0'); $perQty = (float) ($r['qty'] ?? 0) / $n; $rowVol = ($r['volume'] !== null && $r['volume'] !== '') ? (float) $r['volume'] : null; $perVol = ($rowVol !== null) ? $rowVol / $n : null; foreach ($bcs as $bc) { $k = $io . '|' . mb_strtolower($bc); if (! isset($agg[$k])) { $agg[$k] = [ 'io' => $io, 'sku' => $bc, 't0' => 0.0, 't0n' => 0, 'any' => 0.0, 'anyn' => 0, 't0vol' => 0.0, 't0voln' => 0, 'anyvol' => 0.0, 'anyvoln' => 0, 'shopid' => null, 'name' => null, 'wh' => null, 'l' => null, 'w' => null, 'h' => null, 'weight' => null, 'supplier' => null, ]; } if ($isT0) { $agg[$k]['t0'] += $perQty; $agg[$k]['t0n']++; if ($perVol !== null) { $agg[$k]['t0vol'] += $perVol; $agg[$k]['t0voln']++; } } $agg[$k]['any'] += $perQty; $agg[$k]['anyn']++; if ($perVol !== null) { $agg[$k]['anyvol'] += $perVol; $agg[$k]['anyvoln']++; } // 名称/长宽高/供应商沿用整行值(共享):任意行回填一次 if (empty($agg[$k]['name']) && ! empty($r['sku_name'])) { $agg[$k]['name'] = $r['sku_name']; } if (empty($agg[$k]['shopid']) && ! empty($r['shop_i_id'])) { $agg[$k]['shopid'] = $r['shop_i_id']; } if (empty($agg[$k]['wh']) && ! empty($r['wareHoursName'])) { $agg[$k]['wh'] = $r['wareHoursName']; } foreach (['l', 'w', 'h', 'weight'] as $ff) { if (empty($agg[$k][$ff]) && ! empty($r[$ff])) { $agg[$k][$ff] = $r[$ff]; } } if (empty($agg[$k]['supplier']) && ! empty($r['supplier_name'])) { $agg[$k]['supplier'] = $r['supplier_name']; } } } } $out = []; foreach ($agg as $a) { $qty = $a['t0n'] > 0 ? $a['t0'] : ($a['anyn'] > 0 ? $a['any'] / $a['anyn'] : 0); $qty = (int) round($qty); if ($qty < 1) { $qty = 1; } // 体积:type=0 各条码分摊之和优先;否则取任一 type 的均值(去 type 重复) $vol = $a['t0voln'] > 0 ? round($a['t0vol'], 4) : ($a['anyvoln'] > 0 ? round($a['anyvol'] / $a['anyvoln'], 4) : null); $out[$a['io']][] = [ 'id' => null, 'sku' => $a['sku'], 'iid' => null, 'shopid' => $a['shopid'], 'name' => $a['name'], 'qty' => $qty, 'amount' => null, 'warehouse' => $a['wh'], 'l' => $a['l'], 'w' => $a['w'], 'h' => $a['h'], 'vol' => $vol, 'volume_is_total' => true, // 视图 weight 是整行合计重量,不能再乘这一行的商品数量。 'weight' => $a['weight'], 'weight_is_total' => true, 'supplier' => $a['supplier'], ]; } if ($multi !== []) { $this->appendComboParts($multi, $out); } return $out; } /** * 组合件拆件(对齐工作平台导出明细):视图一行逗号拼接多个部件条码时,每个部件一行—— * 名称/长宽高取 SKU 资料,体积=长×宽×高; * 数量:订单商品 → 运费逐件重量÷SKU单重 → 整数均分,前两者须部件合计=整行数量才采用; * 同时带整行 名称/体积(按部件数均摊)/长宽高(m_*),供合并口径使用(工作平台合并取整行值)。 * 同一出库单有 type=0 行只用 type=0,否则用最小 type,避免 type=3 等重复行重复计数。 */ private function appendComboParts(array $multi, array &$out): void { $sel = []; $bcAll = []; foreach ($multi as $io => $rows) { $types = array_values(array_unique(array_map(fn ($r) => $r['t'], $rows))); $useT = in_array('0', $types, true) ? '0' : min($types); foreach ($rows as $r) { if ($r['t'] === $useT) { $sel[(string) $io][] = $r; foreach ($r['bcs'] as $b) { $bcAll[$b] = true; } } } } $ioKeys = array_map('strval', array_keys($sel)); $o2io = []; foreach (array_chunk($ioKeys, 800) as $ck) { $ph = implode(',', array_fill(0, count($ck), '?')); foreach ($this->selectWithReconnect('SELECT io_id, o_id FROM ' . self::OUTBOUND . " WHERE io_id IN ({$ph})", $ck) as $r) { $o = (string) ($r['o_id'] ?? ''); if ($o !== '') { $o2io[$o][(string) $r['io_id']] = true; } } } $ordQty = []; foreach (array_chunk(array_map('strval', array_keys($o2io)), 800) as $ck) { $ph = implode(',', array_fill(0, count($ck), '?')); foreach ($this->selectWithReconnect("SELECT o_id, sku_id, qty FROM rpt.jst_OrderItem WHERE o_id IN ({$ph})", $ck) as $r) { $k = mb_strtolower(trim((string) ($r['sku_id'] ?? ''))); foreach ($o2io[(string) $r['o_id']] ?? [] as $io => $_) { $ordQty[(string) $io][$k] = ($ordQty[(string) $io][$k] ?? 0) + (float) ($r['qty'] ?? 0); } } } $fysW = []; foreach (array_chunk($ioKeys, 800) as $ck) { $ph = implode(',', array_fill(0, count($ck), '?')); foreach ($this->selectWithReconnect("SELECT io_id, sku_id, weight FROM rpt.fys_jstFreightCostDetail WHERE io_id IN ({$ph})", $ck) as $r) { $k = mb_strtolower(trim((string) ($r['sku_id'] ?? ''))); $fysW[(string) $r['io_id']][$k] = ($fysW[(string) $r['io_id']][$k] ?? 0) + (float) ($r['weight'] ?? 0); } } $skuL = []; foreach ($this->loadSkus(array_map('strval', array_keys($bcAll))) as $k => $v) { $skuL[mb_strtolower((string) $k)] = $v; } $raw = fn ($v) => ($v === null || trim((string) $v) === '') ? null : (float) $v; foreach ($sel as $io => $rows) { $io = (string) $io; $parts = []; foreach ($rows as $r) { $bcs = $r['bcs']; $n = count($bcs); $q = $this->partQty($bcs, (int) round($r['qty']), $ordQty[$io] ?? [], $fysW[$io] ?? [], $skuL); $rowVol = $raw($r['vol']); foreach ($bcs as $i => $bc) { $lk = mb_strtolower($bc); $s = $skuL[$lk] ?? []; $L = $this->nz($s['l'] ?? null); $W = $this->nz($s['w'] ?? null); $H = $this->nz($s['h'] ?? null); if (! isset($parts[$lk])) { $parts[$lk] = [ 'id' => null, 'sku' => $bc, 'iid' => $s['iid'] ?? null, 'shopid' => ($r['shopid'] ?? null) ?: null, 'name' => ($s['name'] ?? null) ?: $r['name'], 'qty' => 0, 'amount' => null, 'warehouse' => ($r['wh'] ?? null) ?: null, 'l' => $L, 'w' => $W, 'h' => $H, 'vol' => ($L && $W && $H) ? round($L * $W * $H, 4) : null, 'weight' => $s['weight'] ?? null, 'supplier' => ($r['supplier'] ?? null) ?: null, 'mname' => $r['name'], 'mvol' => null, 'ml' => $raw($r['l']), 'mw' => $raw($r['w']), 'mh' => $raw($r['h']), ]; } $parts[$lk]['qty'] += $q[$i]; if ($rowVol !== null) { $parts[$lk]['mvol'] = ($parts[$lk]['mvol'] ?? 0) + $rowVol / $n; } } } foreach ($parts as $lk => $p) { $p['mvol'] = $p['mvol'] !== null ? round($p['mvol'], 4) : null; $hit = false; foreach ($out[$io] ?? [] as $idx => $it) { if (mb_strtolower((string) $it['sku']) === $lk) { $out[$io][$idx]['qty'] += $p['qty']; $hit = true; break; } } if (! $hit) { $out[$io][] = $p; } } } } /** 组合件部件数量:订单商品 → 运费逐件重量÷SKU单重 → 整数均分;前两者须合计=整行数量。 */ private function partQty(array $bcs, int $rowQty, array $ord, array $fys, array $skuL): array { $n = count($bcs); $keys = array_map(fn ($b) => mb_strtolower($b), $bcs); $a = []; foreach ($keys as $k) { if (! isset($ord[$k])) { $a = null; break; } $a[] = (int) round($ord[$k]); } if ($a !== null && array_sum($a) === $rowQty && min($a) > 0) { return $a; } $b = []; foreach ($keys as $k) { $sw = (float) ($skuL[$k]['weight'] ?? 0); if (! isset($fys[$k]) || $sw <= 0) { $b = null; break; } $b[] = (int) round($fys[$k] / $sw); } if ($b !== null && array_sum($b) === $rowQty && min($b) > 0) { return $b; } $total = max($rowQty, 0); $base = intdiv($total, $n); $rem = $total - $base * $n; $c = []; foreach ($keys as $i => $_) { $c[] = $base + ($i < $rem ? 1 : 0); } return $c; } private function nz(mixed $v): ?float { if ($v === null || trim((string) $v) === '') { return null; } $f = (float) $v; return $f == 0.0 ? null : $f; } /** 收货省市区统一取发货数据视图(与工作平台一致),视图无值时保留原值。 */ private function withViewAddr(string $io, array $pkg): array { if ($io !== '' && trim((string) ($pkg['shop_name'] ?? '')) === '' && isset($this->ioShop[$io])) { $pkg['shop_name'] = $this->ioShop[$io]; } $a = ($io !== '') ? ($this->ioAddr[$io] ?? []) : []; foreach (['st' => 'r_state', 'ci' => 'r_city', 'di' => 'r_district'] as $ak => $pk) { if (isset($a[$ak]) && $a[$ak] !== '') { $pkg[$pk] = $a[$ak]; } } return $pkg; } private function collectSkuIds(array ...$maps): array { $ids = []; foreach ($maps as $map) { foreach ($map as $items) { foreach ($items as $it) { if (! empty($it['sku'])) { $ids[(string) $it['sku']] = true; } } } } return array_keys($ids); } private function push(int $sourceId, int $skuSourceId, array $payload): void { $payload['source_id'] = $sourceId; $payload['sku_source_id'] = $skuSourceId; $this->buffer[] = $payload; if (count($this->buffer) >= self::FLUSH) { $this->flush(); } } private function packageRow(int $sourceId, int $skuSourceId, array $payload): array { $payload['source_id'] = $sourceId; $payload['sku_source_id'] = $skuSourceId; return $payload; } /** @param list> $rows */ private function writePackage(int $sourceId, array $rows, bool $hasFreight, bool $hasItems, array $syntheticSkuIds): void { $fromView = $this->itemsFromView; $this->itemsFromView = false; if (! $this->replaceWindow) { $rows = app(ShippingWeightPrecision::class)->shipmentRows($rows); foreach ($rows as $row) { $this->push($sourceId, (int) $row['sku_source_id'], $row); } return; } $this->replacementRowCount -= count($this->replacementPackages[$sourceId] ?? []); $this->replacementPackages[$sourceId] = $rows; $this->replacementHasFreight[$sourceId] = $hasFreight; $this->replacementHasItems[$sourceId] = $hasItems; $this->replacementSyntheticSkuIds[$sourceId] = $syntheticSkuIds; $this->replacementFromView[$sourceId] = $fromView; $this->replacementRowCount += count($rows); if ($this->replacementRowCount >= self::FLUSH) { $this->flushReplacements(); } } private function flushPending(): void { if ($this->replaceWindow) { $this->flushReplacements(); } else { $this->flush(); } } private function flushReplacements(): void { if ($this->replacementPackages === []) { return; } $packages = $this->replacementPackages; $hasFreight = $this->replacementHasFreight; $hasItems = $this->replacementHasItems; $syntheticSkuIds = $this->replacementSyntheticSkuIds; $fromView = $this->replacementFromView; $this->db->transaction(function () use ($packages, $hasFreight, $hasItems, $syntheticSkuIds, $fromView): void { $ids = array_keys($packages); $previous = []; $previousItems = []; $oldAmountSkuIds = []; $oldHasItems = []; $oldRows = $this->db->table('jst_oms_shipping')->whereIn('source_id', $ids) ->select(array_merge( ['source_id', 'sku_source_id', 'express_no', 'express_name2', 'freight', 'settle_freight', 'weight_kg', 'settle_weight_kg', 'item_id', 'barcode', 'product_name', 'product_code', 'qty', 'amount'], self::PRESERVED_PACKAGE_FIELDS, self::PRESERVED_CONTACT_FIELDS, self::PRESERVED_ITEM_FIELDS, )) ->get(); foreach ($oldRows as $oldRow) { $id = (int) $oldRow->source_id; $row = (array) $oldRow; $previousItems[$id][(int) $oldRow->sku_source_id] = $row; if ($row['amount'] !== null) { $oldAmountSkuIds[$id][(int) $oldRow->sku_source_id] = true; } foreach (['item_id', 'barcode', 'product_name', 'product_code', 'qty', 'amount', 'finished_barcode', 'finished_name', 'finished_supplier'] as $field) { if ($row[$field] !== null && $row[$field] !== '') { $oldHasItems[$id] = true; break; } } if (! isset($previous[$id])) { $previous[$id] = $row; continue; } foreach (array_merge( ['freight', 'settle_freight', 'weight_kg', 'settle_weight_kg', 'express_no', 'express_name2'], self::PRESERVED_PACKAGE_FIELDS, self::PRESERVED_CONTACT_FIELDS, ) as $field) { if (($previous[$id][$field] ?? null) === null || $previous[$id][$field] === '') { $previous[$id][$field] = $row[$field]; } } } $rows = []; $replaceIds = []; $refresh = []; foreach ($packages as $id => $packageRows) { if (! ($hasItems[$id] ?? false) && ($oldHasItems[$id] ?? false)) { $this->packagesRetainedForMissingItems++; $refresh[$id] = $packageRows[0] ?? []; continue; } $unmatchedOldAmounts = $oldAmountSkuIds[$id] ?? []; $unsafeAmount = false; // 旧金额按条码索引:商品行 ID 变了但条码相同时沿用旧金额 $oldAmountByBarcode = []; $oldBarcodes = []; foreach ($previousItems[$id] ?? [] as $oldSkuId => $oldRowItem) { $oldKey = mb_strtolower(trim((string) ($oldRowItem['barcode'] ?? ''))); if ($oldKey === '') { continue; } $oldBarcodes[$oldKey] = true; if ($oldRowItem['amount'] !== null && ! isset($oldAmountByBarcode[$oldKey])) { $oldAmountByBarcode[$oldKey] = [$oldSkuId, $oldRowItem['amount']]; } } $newBarcodes = []; foreach ($packageRows as $newRow) { $newKey = mb_strtolower(trim((string) ($newRow['barcode'] ?? ''))); if ($newKey !== '') { $newBarcodes[$newKey] = true; } } foreach ($packageRows as &$packageRow) { $skuId = (int) $packageRow['sku_source_id']; $oldItem = $previousItems[$id][$skuId] ?? null; $barcodeKey = mb_strtolower(trim((string) ($packageRow['barcode'] ?? ''))); if (isset($syntheticSkuIds[$id][$skuId]) && $oldItem !== null && mb_strtolower(trim((string) ($oldItem['barcode'] ?? ''))) !== $barcodeKey) { // Synthetic IDs depend on row order, which the upstream view does not promise. // Match the amount by barcode before deciding whether an update is unsafe. $oldItem = null; } if ($packageRow['amount'] !== null) { unset($unmatchedOldAmounts[$skuId]); continue; } if ($oldItem === null || $oldItem['amount'] === null) { if ($barcodeKey !== '' && isset($oldAmountByBarcode[$barcodeKey])) { [$matchedOldSkuId, $matchedAmount] = $oldAmountByBarcode[$barcodeKey]; $packageRow['amount'] = $matchedAmount; unset($unmatchedOldAmounts[$matchedOldSkuId], $oldAmountByBarcode[$barcodeKey]); $this->amountsMatchedByBarcode++; } continue; } $packageRow['amount'] = $oldItem['amount']; unset($unmatchedOldAmounts[$skuId], $oldAmountByBarcode[$barcodeKey]); } unset($packageRow); if (! $unsafeAmount && $unmatchedOldAmounts !== []) { foreach ($packageRows as $packageRow) { if ($packageRow['amount'] === null) { $unsafeAmount = true; break; } } } if ($unsafeAmount && $oldBarcodes !== [] && $newBarcodes !== [] && array_intersect_key($oldBarcodes, $newBarcodes) === []) { // 新旧商品完全不同:旧记录是错配商品(如把同订单其它包裹的商品挂到本单号),旧金额不属于本包裹,按新商品覆盖 $unsafeAmount = false; $this->packagesItemsCorrected++; } elseif ($unsafeAmount && ($fromView[$id] ?? false) && $oldBarcodes !== [] && $newBarcodes !== [] && $oldBarcodes != $newBarcodes) { // 新商品取自出库单实发明细且条码集合与旧记录不同(旧记录多为订单商品兜底:整件/原商品/配件母件等): // 以出库单为准覆盖;条码相同的行已按条码沿用旧金额,其余旧金额属于错配商品,不再保留。 $unsafeAmount = false; $this->packagesItemsCorrected++; } if ($unsafeAmount) { $this->packagesRetainedForUnmatchedAmount++; $refresh[$id] = $packageRows[0] ?? []; continue; } $replaceIds[] = $id; foreach ($packageRows as &$packageRow) { foreach (self::PRESERVED_PACKAGE_FIELDS as $field) { $packageRow[$field] ??= null; } foreach (self::PRESERVED_ITEM_FIELDS as $field) { $packageRow[$field] = $previousItems[$id][(int) $packageRow['sku_source_id']][$field] ?? null; } } unset($packageRow); if (isset($previous[$id])) { foreach (self::PRESERVED_PACKAGE_FIELDS as $field) { $packageRows[0][$field] = $previous[$id][$field] ?? null; } if (! empty($previous[$id]['express_no']) && ! empty($packageRows[0]['express_no']) && ltrim($previous[$id]['express_no'], '@') !== ltrim($packageRows[0]['express_no'], '@')) { $packageRows[0]['front_no'] = $previous[$id]['express_no']; } foreach (self::PRESERVED_CONTACT_FIELDS as $field) { if (($packageRows[0][$field] ?? null) === null || $packageRows[0][$field] === '') { $packageRows[0][$field] = $previous[$id][$field] ?? null; } } if ($this->skipFreight) { $packageRows[0] = $this->withPreservedFreight($packageRows[0], $previous[$id]); } elseif (! ($hasFreight[$id] ?? false)) { $packageRows[0] = $this->withPreservedCharges($packageRows[0], $previous[$id], false); } } array_push($rows, ...$packageRows); } $this->refreshRetainedPackages($refresh, $previous); if ($replaceIds === []) { return; } $this->db->table('jst_oms_shipping')->whereIn('source_id', $replaceIds)->delete(); $rows = app(ShippingWeightPrecision::class)->shipmentRows($rows); foreach (array_chunk($rows, self::FLUSH) as $chunk) { $this->db->table('jst_oms_shipping')->insert($chunk); } }); $this->replacementPackages = []; $this->replacementHasFreight = []; $this->replacementHasItems = []; $this->replacementSyntheticSkuIds = []; $this->replacementFromView = []; $this->replacementRowCount = 0; } private function flush(): void { if ($this->buffer === []) { return; } $this->db->table('jst_oms_shipping')->insertOrIgnore($this->buffer); $this->buffer = []; } private function isPricePatch(?string $name): bool { if ($name === null || $name === '') { return false; } return str_contains($name, '补收差价') || str_contains($name, '差价专用'); } /** * 线上发货标签排除口径(对齐工作平台): * 工作平台只排除"刷单/批发/纯售后"这类无实物的线上发货虚拟单,以及京东品牌自营的京仓单(京东仓发货); * 其余云仓/京仓(CLPS/ECLP)真实发货工作平台是收进的,不能排除。 */ private function excludedByLabel(?string $labels): bool { if ($labels === null || $labels === '') { return false; } if (! str_contains($labels, '线上发货')) { return false; } // 京东品牌自营的京仓单(ECLP/京仓订单 + 品牌自营):货由京东仓发出,子订单状态是「外部发货」, // 工作平台不收(2026-11 比对 1–27 日 32 单全部如此),排除。 if (str_contains($labels, '品牌自营')) { $tags = array_map('trim', preg_split('/[,,;;|]+/u', $labels) ?: []); if (in_array('线上发货', $tags, true) && in_array('品牌自营', $tags, true) && array_intersect(['京仓订单', 'ECLP订单', 'ECLP'], $tags) !== []) { return true; } } // 云仓/京仓真实发货:工作平台收进,保留 if (str_contains($labels, '云仓订单') || str_contains($labels, '京仓订单') || str_contains($labels, 'CLPS') || str_contains($labels, 'ECLP')) { return false; } 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 { $out = []; foreach (array_chunk($skuIds, 800) as $chunk) { if ($chunk === []) { continue; } $ph = implode(',', array_fill(0, count($chunk), '?')); foreach ($this->selectWithReconnect("SELECT sku_id, l, w, h, pack_volume, weight, supplier_name, name, i_id FROM rpt.jst_sku WHERE sku_id IN ({$ph})", $chunk) as $r) { $out[mb_strtolower(trim((string) $r['sku_id']))] = [ 'l' => $r['l'] ?? null, 'w' => $r['w'] ?? null, 'h' => $r['h'] ?? null, 'vol' => $r['pack_volume'] ?? null, 'weight' => $r['weight'] ?? null, 'supplier' => $r['supplier_name'] ?? null, 'name' => $r['name'] ?? null, 'iid' => $r['i_id'] ?? null, ]; } } return $out; } /** @return array so_id|expressNo => 运费 (含 so_id| 兜底键) */ private function loadFreight(array $soIds): array { $out = []; $first = []; $tracksBySo = []; foreach (array_chunk($soIds, 800) as $chunk) { if ($chunk === []) { continue; } $ph = implode(',', array_fill(0, count($chunk), '?')); $sql = 'SELECT so_id, expressNo, SUM(freightCost) AS cost, SUM(weight) AS w, ' . 'MAX(expressName) AS name, MAX(receiver_state) AS state ' . "FROM rpt.fys_jstFreightCostDetail WHERE so_id IN ({$ph}) GROUP BY so_id, expressNo"; foreach ($this->selectWithReconnect($sql, $chunk) as $r) { $so = (string) $r['so_id']; // 快递单号去@归一,与包裹单号(emittedTrack/doneTrack 等)同一口径 $expno = ltrim(trim((string) ($r['expressNo'] ?? '')), '@'); $val = ['cost' => $r['cost'] ?? null, 'w' => $r['w'] ?? null, 'name' => $r['name'] ?? null, 'state' => $r['state'] ?? null, 'no' => $expno ?: null]; $first[$so] ??= $val; if ($expno === '') { continue; } $tracksBySo[$so][$expno] = true; $key = $so . '|' . $expno; // 同一包裹可能同时有带@和不带@两条(换单前后),保留有运费的那条,不相加 if (! isset($out[$key]) || ! isset($out[$key]['cost'])) { $out[$key] = $val; } } } // 只有一个快递单号的交易单号才允许按交易单号兜底;多包裹订单不能借用其它包裹的运费、单号和快递名称 foreach ($first as $so => $val) { if (count($tracksBySo[$so] ?? []) <= 1) { $out[$so . '|'] = $val; } } return $out; } /** * 聚水潭运费明细里每个包裹(交易单号+快递单号)的 sku,写入 $this->fysPackageSkus; * 返回 [交易单号|快递单号 => [['sku' => ...], ...]] 供 loadSkus 一并加载尺寸重量。 */ private function loadFysPackageSkus(array $soIds): array { $this->fysPackageSkus = []; $this->fysSoTrackCount = []; foreach (array_chunk($soIds, 800) as $chunk) { if ($chunk === []) { continue; } $ph = implode(',', array_fill(0, count($chunk), '?')); $sql = 'SELECT so_id, expressNo, sku_id, COUNT(*) AS n ' . "FROM rpt.fys_jstFreightCostDetail WHERE so_id IN ({$ph}) GROUP BY so_id, expressNo, sku_id"; foreach ($this->selectWithReconnect($sql, $chunk) as $r) { $expno = ltrim(trim((string) ($r['expressNo'] ?? '')), '@'); $sku = trim((string) ($r['sku_id'] ?? '')); if ($expno === '' || $sku === '') { continue; } $key = ((string) $r['so_id']) . '|' . $expno; $this->fysPackageSkus[$key][$sku] = ($this->fysPackageSkus[$key][$sku] ?? 0) + max((int) ($r['n'] ?? 1), 1); } } $items = []; foreach (array_keys($this->fysPackageSkus) as $key) { $so = substr($key, 0, (int) strrpos($key, '|')); $this->fysSoTrackCount[$so] = ($this->fysSoTrackCount[$so] ?? 0) + 1; } foreach ($this->fysPackageSkus as $key => $skus) { foreach (array_keys($skus) as $sku) { $items[$key][] = ['sku' => (string) $sku]; } } return $items; } /** * 窗口内本次未扫到的旧包裹:若其快递单号已由本次其它包裹(新来源键)吐出,说明是被取代的旧记录 * (如凌晨同步时发货明细未到、先按自动发货仓/出库单兜底入库,之后发货明细到齐换成发货明细来源),删除以免重复和残留空白; * 其余仍保留并计数,需按源键核对。 */ private function countUnseenMirrorPackages(string $fromS, string $toS): int { $unseen = 0; $superseded = []; $rows = $this->db->table('jst_oms_shipping') ->where('ship_time', '>=', $fromS)->where('ship_time', '<', $toS) ->selectRaw('source_id, MAX(express_no) AS express_no, MAX(trade_no) AS trade_no')->groupBy('source_id')->get(); foreach ($rows as $row) { $id = (int) $row->source_id; if (isset($this->seenSourceIds[$id])) { continue; } $tk = ltrim(trim((string) ($row->express_no ?? '')), '@'); if ($tk !== '' && isset($this->emittedTrack[$tk])) { $superseded[] = $id; continue; } // 凌晨按自动发货仓入库、当时还没有快递单号的旧包裹:订单之后有了发货明细(改走发货明细来源键), // 或同一交易单号本次已由其它包裹吐出 → 视为被取代 // 出库单兜底/采购退货出库:本次已完整扫描窗口内的出库单与采购退货单,未再出现说明上游已作废、换单或不再收录(工作平台也不再显示) if (($id >= self::PURCHASE_OUT_OFFSET && $this->purchaseScanned > 0) || ($id >= self::OUTBOUND_OFFSET && $id < self::PURCHASE_OUT_OFFSET && $this->outboundScanned > 0)) { $superseded[] = $id; continue; } $so = trim((string) ($row->trade_no ?? '')); $isAuto = $id >= self::AUTOSHIP_OFFSET && $id < self::OUTBOUND_OFFSET; if (($isAuto && isset($this->expressOrderIds[(string) ($id - self::AUTOSHIP_OFFSET)])) || ($tk === '' && $so !== '' && isset($this->emittedSo[$so]))) { $superseded[] = $id; continue; } $unseen++; } foreach (array_chunk($superseded, 500) as $chunk) { $this->db->table('jst_oms_shipping')->whereIn('source_id', $chunk)->delete(); } $this->supersededRemoved = count($superseded); return $unseen; } /** 因商品/金额无法安全替换而保留的旧包裹:包裹级字段(省市区、快递、仓库、店铺等)仍按本次上游刷新,商品与金额不动。 */ private function refreshRetainedPackages(array $refresh, array $previous): void { foreach ($refresh as $id => $new) { $set = []; foreach (self::REFRESHED_PACKAGE_FIELDS as $field) { $v = $new[$field] ?? null; if ($v !== null && trim((string) $v) !== '') { $set[$field] = $v; } } $oldTracking = trim((string) ($previous[$id]['express_no'] ?? '')); if ($oldTracking !== '' && isset($set['express_no']) && ltrim($oldTracking, '@') !== ltrim($set['express_no'], '@')) { $set['front_no'] = $oldTracking; } if ($set !== []) { $this->db->table('jst_oms_shipping')->where('source_id', (int) $id)->update($set); } } } private function withPreservedFreight(array $payload, array $previous): array { $payload = $this->withPreservedCharges($payload, $previous); // Preserving freight must not restore the old tracking number after a waybill change. $payload['express_name2'] = $previous['express_name2'] ?? $payload['express_name2']; return $payload; } private function withPreservedCharges(array $payload, array $previous, bool $includeNull = true): array { foreach (['freight', 'settle_freight', 'weight_kg', 'settle_weight_kg'] as $field) { if ($includeNull || $previous[$field] !== null) { $payload[$field] = $previous[$field]; } } return $payload; } /** jst_oms_shipping 文本列长度上限:上游偶有超长值(如组合装商品ID),超长截断而不是整批写入失败。 */ private const COLUMN_LIMITS = [ 'express_no' => 64, 'trade_no' => 64, 'item_id' => 64, 'barcode' => 128, 'product_name' => 512, 'receiver_state' => 64, 'receiver_city' => 64, 'receiver_district' => 64, 'receiver_name' => 128, 'receiver_mobile' => 64, 'receiver_phone' => 64, 'shop_name' => 255, 'express_name1' => 128, 'express_name2' => 128, 'warehouse_name' => 128, 'supplier_name' => 128, 'platform' => 64, 'product_code' => 128, 'pkg_count' => 32, 'm_name' => 500, ]; private function cleanPayload(array $data): array { foreach ($data as $k => $v) { if (is_string($v)) { $v = $this->cleanStr($v); $limit = self::COLUMN_LIMITS[$k] ?? null; if ($limit !== null && mb_strlen($v) > $limit) { $v = mb_substr($v, 0, $limit); } $data[$k] = $v; } } return $data; } /** * 订单商品表里平台原始商品行(数量 0、金额 0)并没有实际出库,聚水潭工作平台也不显示; * 包裹已有实发商品时不写入这类行,避免多出一个"条码"(其实是平台商品编号)。 * * @param list> $items * @return list> */ private function dropZeroQtyPlaceholders(array $items): array { $zero = static fn ($v): bool => $v !== null && $v !== '' && is_numeric($v) && (float) $v == 0.0; $placeholder = static fn (array $it): bool => $zero($it['qty'] ?? null) && (($it['amount'] ?? null) === null || ($it['amount'] ?? null) === '' || $zero($it['amount'])); $keep = array_values(array_filter($items, static fn (array $it): bool => ! $placeholder($it))); $hasShipped = array_filter($keep, static fn (array $it): bool => is_numeric($it['qty'] ?? null) && (float) $it['qty'] > 0); return ($hasShipped !== [] && count($keep) < count($items)) ? $keep : $items; } private function cleanStr(string $v): string { $v = str_replace("\0", '', $v); $clean = @iconv('UTF-8', 'UTF-8//IGNORE', $v); if ($clean === false) { $clean = mb_convert_encoding($v, 'UTF-8', 'UTF-8'); } return $clean; } /** * 发货时间校正:仓库次日才出库的包裹,同步时出库单还没生成,发货时间先落成发货明细(打单)时间; * 后续同步若走"保留旧包裹"分支不会改写。这里按快递单号对齐出库单 io_date(=聚水潭发货/出库时间), * 只把偏早的发货时间往后校正(相差 1 分钟~7 天)。同一单号有多张有效出库单时须先确认对应包裹。 */ public function fixShipTimes(string $fromS, string $toS): int { return $this->alignWithOutbound($fromS, $toS)['ship_time']; } /** 副本库缺列(如没有 weight/f_weight)的报错:只有这种情况才允许退回不带重量的查询。 */ private function isMissingColumnError(Throwable $e): bool { $m = mb_strtolower($e->getMessage()); return str_contains($m, 'invalid column name') || str_contains($m, 'unknown column') || str_contains($m, '列名') || (str_contains($m, 'column') && (str_contains($m, 'weight') || str_contains($m, 'not found'))); } /** * 按销售出库单对齐包裹级字段(聚水潭"销售出库单"界面口径): * - 发货时间 = 出库时间 io_date(只往后校正,见 fixShipTimes) * - 线上重量 = 出库单 weight(预估重量),实称重量 = 出库单 f_weight(没称重为空) * 发货明细 e.weight 未称重时是预估重量、称重后才变实称,不能直接当实称; * 商品资料单重×数量也不等于聚水潭预估重量。两个重量只写在包裹第一行(合并模式按包裹求和)。 * * @return array{ship_time:int, weight:int, swapped:int, cleared:int} */ public function alignWithOutbound(string $fromS, string $toS): array { $ioTo = Carbon::parse($toS)->addDays(3)->format('Y-m-d H:i:s'); $withWeight = true; // 按天读取后立即整理索引,不在内存里同时保留整月原始出库行。 // 只有副本库确实没有重量列时才退回"只校正发货时间";超时等其它错误直接抛出, // 不能悄悄跳过重量校正(否则发货明细里的预估重量会一直留在实称里)。 $best = []; $multiple = []; $bySo = []; // 线上订单号 => [有效出库单的快递单号 => 快递公司] $cur = Carbon::parse($fromS); $end = Carbon::parse($ioTo); while ($cur->lt($end)) { $next = $cur->copy()->addDay(); if ($next->gt($end)) { $next = $end->copy(); } $bind = [$cur->format('Y-m-d H:i:s'), $next->format('Y-m-d H:i:s')]; $part = null; if ($withWeight) { try { $part = $this->selectWithReconnect( 'SELECT so.l_id, so.io_date, so.status, so.weight, so.f_weight, so.io_id, so.so_id, so.logistics_company FROM ' . self::OUTBOUND . ' so WHERE so.io_date >= ? AND so.io_date < ?', $bind, ); } catch (Throwable $e) { if (! $this->isMissingColumnError($e)) { throw $e; } $withWeight = false; } } if ($part === null) { $part = $this->selectWithReconnect( 'SELECT so.l_id, so.io_date, so.status, so.io_id, so.so_id, so.logistics_company FROM ' . self::OUTBOUND . ' so WHERE so.io_date >= ? AND so.io_date < ?', $bind, ); } $part = app(ShippingWeightPrecision::class)->outboundRows($part); foreach ($part as $r) { $r = (array) $r; $l = ltrim(trim((string) ($r['l_id'] ?? '')), '@'); $d = $this->ts($r['io_date'] ?? null); if ($l === '' || $d === null) { continue; } $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; $so = trim((string) ($r['so_id'] ?? '')); $candidate = [$rk, $d, $hasW, $w > 0 ? round($w, 4) : null, $fw > 0 ? round($fw, 4) : null, $io, $so]; if ($ok && $so !== '') { $bySo[$so][$l] = trim((string) ($r['logistics_company'] ?? '')); } 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) { $best[$l] = $candidate; } } unset($part); $cur = $next; } if ($best === []) { return ['ship_time' => 0, 'weight' => 0, 'swapped' => 0, 'cleared' => 0]; } $mirrorFrom = Carbon::parse($fromS)->subDays(7)->format('Y-m-d H:i:s'); $swapped = $this->swapReplacedTracking($fromS, $toS, $best, $bySo); unset($bySo); // 一个快递单号只有一张出库单、却挂在几个订单(source_id)上(合单发货;或同包裹另一个订单没有商品明细): // 出库单重量是整包重量,只能记一次,记在有商品明细的那个订单的第一行(和运费核算的主包裹一致)。 // 同一单号多张有效出库单(分批发货)仍按各自出库单各记各的。 $itemSid = []; // 快递单号 => 最早一行有商品明细的 source_id $this->db->table('jst_oms_shipping') ->select(['id', 'source_id', 'express_no', 'trade_no', 'ship_time']) ->where('ship_time', '>=', $mirrorFrom)->where('ship_time', '<', $toS) ->whereNotNull('express_no')->whereNotNull('barcode')->where('barcode', '<>', '') ->chunkById(20000, function ($chunk) use (&$itemSid, $best, $multiple): void { foreach ($chunk as $row) { $l = ltrim(trim((string) $row->express_no), '@'); if ($l !== '' && isset($best[$l]) && ! isset($multiple[$l]) && ! isset($itemSid[$l]) && $this->sameShipment($best[$l], (string) $row->trade_no, (string) $row->ship_time)) { $itemSid[$l] = (int) $row->source_id; } } }, 'id'); $fixTime = []; $orphans = []; // 快递单号 => [行 id] $owner = []; // 单号 => 唯一的主包裹 $weighed = []; // 包裹或单号已经写入整包重量 $seenSid = []; // source_id => 已校正时间 $setWeight = []; // [id, online, actual] $clearIds = []; // 不该带重量的行 -> 置空 $this->db->table('jst_oms_shipping') ->select(['id', 'source_id', 'express_no', 'express_name1', 'trade_no', 'ship_time', 'online_weight', 'actual_weight']) ->where('ship_time', '>=', $mirrorFrom)->where('ship_time', '<', $toS) ->whereNotNull('express_no') ->chunkById(20000, function ($chunk) use (&$fixTime, &$seenSid, &$setWeight, &$clearIds, &$orphans, $best, $multiple, $itemSid, &$owner, &$weighed): void { $precision = app(ShippingWeightPrecision::class); $corrections = $precision->corrections($chunk->map(static fn ($row) => (array) $row)->all()); foreach ($chunk as $row) { $sid = (int) $row->source_id; $l = ltrim(trim((string) $row->express_no), '@'); if ($l === '' || ! isset($best[$l])) { continue; } $b = $this->outboundForMirrorRow($sid, (string) $row->ship_time, $best[$l], $multiple[$l] ?? []); if ($b === null && isset($multiple[$l]) && ($row->online_weight !== null || $row->actual_weight !== null)) { $orphans[$l][] = (int) $row->id; // 分批出库的单号里对不上任何一张出库单的行 } if ($b === null || (! isset($multiple[$l]) && ! $this->sameShipment($b, (string) $row->trade_no, (string) $row->ship_time))) { continue; } if (! isset($seenSid[$sid])) { $seenSid[$sid] = true; $diff = strtotime($b[1]) - strtotime((string) $row->ship_time); if ($diff >= 60 && $diff <= 7 * 86400) { $fixTime[$b[1]][] = $sid; } } if (! $b[2]) { continue; } $split = isset($multiple[$l]); // 分批出库:每张出库单的重量只记一次(同一张出库单被两个包裹行重复对上时只记第一个) $key = $split ? 'i' . $b[5] : 'l' . $l; $own = $split ? ($owner[$key] ??= $sid) : ($owner[$l] ??= ($itemSid[$l] ?? $sid)); if ($sid !== $own || isset($weighed[$key])) { if ($row->online_weight !== null || $row->actual_weight !== null) { $clearIds[] = (int) $row->id; } continue; } $weighed[$key] = true; $confirmed = $precision->correction((array) $row, $corrections); if ($confirmed !== null && $confirmed['online_weight'] !== null) $b[3] = (float) $confirmed['online_weight']; $on = $row->online_weight === null ? null : round((float) $row->online_weight, 4); $ac = $row->actual_weight === null ? null : round((float) $row->actual_weight, 4); if ($on !== $b[3] || $ac !== $b[4]) { $setWeight[] = [(int) $row->id, $b[3], $b[4]]; } } }, 'id'); // 分批出库的每张出库单都已记上重量,其余对不上的行(多出来的空行/旧包裹)不能再带重量 foreach ($orphans as $l => $ids) { $all = true; foreach (array_keys($multiple[$l]) as $io) { $all = $all && isset($weighed['i' . $io]); } if ($all) { array_push($clearIds, ...$ids); } } unset($best, $multiple, $itemSid, $owner, $weighed, $seenSid, $orphans); $nTime = 0; foreach ($fixTime as $new => $ids) { foreach (array_chunk($ids, 500) as $chunk) { $this->db->table('jst_oms_shipping')->whereIn('source_id', $chunk)->update(['ship_time' => $new]); } $nTime += count($ids); } $nWeight = count($setWeight); $groups = []; foreach ($setWeight as $v) { $groups[json_encode([$v[1], $v[2]])][] = $v[0]; } foreach ($groups as $key => $ids) { [$on, $ac] = json_decode($key, true); foreach (array_chunk($ids, 500) as $chunk) { $this->db->table('jst_oms_shipping')->whereIn('id', $chunk)->update(['online_weight' => $on, 'actual_weight' => $ac]); } } $clearIds = array_values(array_unique(array_merge($clearIds, $this->noWaybillLeftoverIds($fromS, $toS, true)))); foreach (array_chunk($clearIds, 500) as $chunk) { $this->db->table('jst_oms_shipping')->whereIn('id', $chunk)->update(['online_weight' => null, 'actual_weight' => null]); } return ['ship_time' => $nTime, 'weight' => $nWeight, 'swapped' => $swapped, 'cleared' => count($clearIds)]; } /** * 没有快递单号的残留行:同一交易单号已经有带快递单号的包裹(工作平台/销售出库单只有那几个包裹), * 这一行不是实际发出的包裹,不能再带重量、也不能再算一次运费。自动发货仓(无需物流)的订单没有带单号的包裹,不受影响。 * * @return list jst_oms_shipping.id */ public function noWaybillLeftoverIds(string $fromS, string $toS, bool $onlyWeighted = false): array { $near = [Carbon::parse($fromS)->subDays(15)->format('Y-m-d H:i:s'), Carbon::parse($toS)->addDays(15)->format('Y-m-d H:i:s')]; $q = $this->db->table('jst_oms_shipping') ->where('ship_time', '>=', $fromS)->where('ship_time', '<', $toS) ->where(fn ($w) => $w->whereNull('express_no')->orWhere('express_no', '')) ->whereNotNull('trade_no')->where('trade_no', '<>', '') ->whereIn('trade_no', fn ($sub) => $sub->select('trade_no')->from('jst_oms_shipping') ->where('ship_time', '>=', $near[0])->where('ship_time', '<', $near[1]) ->whereNotNull('express_no')->where('express_no', '<>', '')); if ($onlyWeighted) { $q->where(fn ($w) => $w->whereNotNull('online_weight')->orWhereNotNull('actual_weight')); } return $q->pluck('id')->map(static fn ($v) => (int) $v)->all(); } /** * 换单没跟上:发货数据里的快递单号在销售出库单里找不到,而同一线上订单在出库单里只有一张有效出库单、 * 换成了另一个单号(如 OLD-TEST-7101 常州中通快运 → SF-TEST-7101 横林顺丰干配)时, * 改成出库单上的单号和快递公司,原单号记进「换单前单号」。只处理一个订单只有一个包裹、新单号在发货数据里还没有的情况。 * * @param array $best 出库单 单号 => 最优出库记录 * @param array> $bySo 线上订单号 => [单号 => 快递公司] */ private function swapReplacedTracking(string $fromS, string $toS, array $best, array $bySo): int { if ($bySo === []) { return 0; } $orphans = []; // 线上订单号 => [source_id => 单号],单号在出库单里找不到的包裹 $this->db->table('jst_oms_shipping') ->select(['id', 'source_id', 'express_no', 'trade_no']) ->where('ship_time', '>=', $fromS)->where('ship_time', '<', $toS) ->whereNotNull('express_no') ->chunkById(20000, function ($chunk) use (&$orphans, $best, $bySo): void { foreach ($chunk as $row) { $l = ltrim(trim((string) $row->express_no), '@'); if ($l === '') { continue; } $so = trim((string) ($row->trade_no ?? '')); if ($so === '' || ! isset($bySo[$so])) { continue; } if (! isset($best[$l])) { $orphans[$so][(int) $row->source_id] = (string) $row->express_no; } } }, 'id'); $n = 0; foreach ($orphans as $so => $packages) { $targets = $bySo[$so]; if (count($packages) !== 1 || count($targets) !== 1) { continue; } $newL = (string) array_key_first($targets); $sid = (int) array_key_first($packages); $oldL = (string) $packages[$sid]; if (ltrim($oldL, '@') === $newL) { continue; } // 只给候选换单查订单索引,避免为整月所有订单保留嵌套包裹数组。 $sourceIds = $this->db->table('jst_oms_shipping')->where('trade_no', $so) ->distinct()->limit(2)->pluck('source_id')->all(); if (count($sourceIds) !== 1 || (int) $sourceIds[0] !== $sid) { continue; } // 新单号可能已在另一个月份;用现有单号索引核对,避免复制成第二个包裹。 if ($this->db->table('jst_oms_shipping')->whereIn('express_no', [$newL, '@' . $newL])->exists()) { continue; } $set = ['express_no' => $newL, 'front_no' => $oldL]; if ($targets[$newL] !== '') { $set['express_name1'] = mb_substr($targets[$newL], 0, 64); } $this->db->table('jst_oms_shipping')->where('source_id', $sid)->update($set); $n++; } return $n; } /** 单号复用且交易单号不同、发货日期相差超过一天时,不套用另一票的重量。 */ private function sameShipment(array $outbound, string $trade, string $shipTime): bool { $so = (string) ($outbound[6] ?? ''); $trade = trim($trade); if ($so === '' || $trade === '' || $so === $trade) { return true; } return abs(strtotime((string) $outbound[1]) - strtotime($shipTime)) <= 86400; } 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)随之更正。 * 这类行多半是占位过滤上线前入库、之后因"金额对不上保留旧包裹"一直没被替换下来的。 * 包裹级字段(重量/运费/结算等)若记在被删的首行上,先挪到保留下来的首行。 */ public function purgeZeroQtyPlaceholders(string $fromS, string $toS): int { $pkgFields = array_merge( ['online_weight', 'actual_weight', 'weight_kg', 'settle_weight_kg', 'freight', 'settle_freight'], self::PRESERVED_PACKAGE_FIELDS, ); $sids = $this->db->table('jst_oms_shipping') ->where('ship_time', '>=', $fromS)->where('ship_time', '<', $toS) ->where('qty', 0) ->where(fn ($q) => $q->whereNull('amount')->orWhere('amount', 0)) ->distinct()->pluck('source_id')->map(fn ($v) => (int) $v)->all(); $packages = 0; foreach (array_chunk($sids, 500) as $chunk) { $rows = $this->db->table('jst_oms_shipping')->whereIn('source_id', $chunk) ->orderBy('id')->get(array_merge(['id', 'source_id', 'qty', 'amount'], $pkgFields)); $by = []; foreach ($rows as $r) { $by[(int) $r->source_id][] = (array) $r; } foreach ($by as $list) { $isPh = static fn (array $r): bool => is_numeric($r['qty']) && (float) $r['qty'] == 0.0 && ($r['amount'] === null || (is_numeric($r['amount']) && (float) $r['amount'] == 0.0)); $keep = array_values(array_filter($list, fn ($r) => ! $isPh($r))); $drop = array_values(array_filter($list, $isPh)); $shipped = array_filter($keep, static fn ($r) => is_numeric($r['qty']) && (float) $r['qty'] > 0); if ($drop === [] || $shipped === []) { continue; } $this->db->transaction(function () use ($list, $keep, $drop, $isPh, $pkgFields): void { if ($isPh($list[0])) { $set = []; foreach ($pkgFields as $f) { $old = $list[0][$f] ?? null; $cur = $keep[0][$f] ?? null; if (($cur === null || $cur === '') && $old !== null && $old !== '') { $set[$f] = $old; } } if ($set !== []) { $this->db->table('jst_oms_shipping')->where('id', $keep[0]['id'])->update($set); } } $this->db->table('jst_oms_shipping')->whereIn('id', array_column($drop, 'id'))->delete(); $this->db->table('jst_oms_shipping')->whereIn('id', array_column($keep, 'id'))->update(['pkg_count' => '1/' . count($keep)]); }); $packages++; } } return $packages; } private function ts(mixed $v): ?string { if ($v === null || $v === '') { return null; } try { return Carbon::parse((string) $v)->format('Y-m-d H:i:s'); } catch (Throwable) { return null; } } private function markRunning(): void { $this->db->table('jst_sync_state')->updateOrInsert( ['dataset_key' => self::DATASET], ['status' => 'running', 'last_started_at' => now(), 'updated_at' => now(), 'created_at' => now()] ); } private function markSucceeded(): void { $this->db->table('jst_sync_state')->where('dataset_key', self::DATASET)->update([ 'status' => 'succeeded', 'last_succeeded_at' => now(), 'last_error' => null, 'watermark' => now(), 'updated_at' => now(), ]); } private function windowDatasetKey(string $prefix, string $fromS, string $toS): string { return $prefix . Carbon::parse($fromS)->format('YmdHis') . '-' . Carbon::parse($toS)->format('YmdHis'); } private function markFreightIncomplete(string $fromS, string $toS): void { $this->db->table('jst_sync_state')->updateOrInsert( ['dataset_key' => $this->windowDatasetKey(self::FREIGHT_DATASET_PREFIX, $fromS, $toS)], [ 'status' => 'pending', 'last_error' => '本窗口采用数量优先补录;上游运费查询已跳过,新记录的运费和结算重量待补齐,空白不代表 0。', 'updated_at' => now(), 'created_at' => now(), ], ); } private function markItemsIncomplete(string $fromS, string $toS): void { $detail = sprintf( '部分日期窗口的商品或金额待核对:%d 个包裹未匹配商品,%d 个包裹金额无法安全匹配,DWS 预载失败 %d 天。', $this->packagesWithoutItems, $this->packagesRetainedForUnmatchedAmount, count($this->dwsFailedDays), ); $this->db->table('jst_sync_state')->updateOrInsert( ['dataset_key' => $this->windowDatasetKey(self::ITEMS_DATASET_PREFIX, $fromS, $toS)], ['status' => 'pending', 'last_error' => $detail, 'updated_at' => now(), 'created_at' => now()], ); } private function markCovered(string $prefix, string $fromS, string $toS): void { $from = Carbon::parse($fromS)->format('YmdHis'); $to = Carbon::parse($toS)->format('YmdHis'); $states = $this->db->table('jst_sync_state')->where('dataset_key', 'like', $prefix . '%') ->where('status', '!=', 'succeeded')->pluck('dataset_key'); foreach ($states as $key) { $range = substr((string) $key, strlen($prefix)); if (! preg_match('/^\d{14}-\d{14}$/', $range)) { continue; } [$pendingFrom, $pendingTo] = explode('-', $range, 2); if ($from <= $pendingFrom && $pendingTo <= $to) { $this->db->table('jst_sync_state')->where('dataset_key', $key)->update([ 'status' => 'succeeded', 'last_error' => null, 'last_succeeded_at' => now(), 'updated_at' => now(), ]); } } } private function markIncompleteWindow(int $unseen): void { $this->db->table('jst_sync_state')->where('dataset_key', self::DATASET)->update([ 'status' => 'partial', 'last_error' => "本窗口尚有 {$unseen} 个镜像包裹未在上游扫描中出现,已保留原记录,需按源键核对。", 'updated_at' => now(), ]); } private function markFailed(string $err): void { $this->db->table('jst_sync_state')->where('dataset_key', self::DATASET)->update([ 'status' => 'failed', 'last_error' => mb_substr($err, 0, 1000), 'updated_at' => now(), ]); } }