diff --git a/app/Console/Commands/SyncUnshippedWaybills.php b/app/Console/Commands/SyncUnshippedWaybills.php index b57114fe4..953a6efc4 100644 --- a/app/Console/Commands/SyncUnshippedWaybills.php +++ b/app/Console/Commands/SyncUnshippedWaybills.php @@ -2,28 +2,76 @@ namespace App\Console\Commands; +use App\Support\UnshippedSourceSynchronizer; use App\Support\UnshippedWaybills; use Illuminate\Console\Command; +use Illuminate\Support\Facades\Cache; +use Throwable; final class SyncUnshippedWaybills extends Command { - protected $signature = 'courier:sync-unshipped-waybills'; - protected $description = '从共享镜像和已导入订单日志重算未发出明细'; + protected $signature = 'courier:sync-unshipped-waybills {--source= : 只刷新指定来源} {--skip-returned : 退回件已刷新时复用该完整结果} {--max-batches=0 : 仓内工单每轮最大批次,0表示至完成}'; + protected $description = '从当前业务副本和发货换单记录刷新未发出明细'; - public function handle(UnshippedWaybills $waybills): int + public function handle(UnshippedWaybills $waybills, UnshippedSourceSynchronizer $sources): int { - $failed = false; - foreach (UnshippedWaybills::SYNC_SOURCES as $source => $label) { - if (!$waybills->sync($source)) { - $warning = $waybills->connection()->table('courier_unshipped_sync')->where('source', $source)->value('warning'); - $this->warn($label.':'.$warning); - $failed = true; - } else { - $state = $waybills->connection()->table('courier_unshipped_sync')->where('source', $source)->first(); - $this->info($label.':'.$state->row_count.' 行,缺单号 '.$state->missing_count.' 行。'); - } + if (app()->environment('production') && !env('FINANCE_BATCH_CONTAINER')) { + $this->error('请通过 run-finance-batch.sh 执行。'); + return self::FAILURE; + } + $selected = (string) $this->option('source'); + if ($selected !== '' && !array_key_exists($selected, UnshippedWaybills::SYNC_SOURCES)) { + $this->error('未知来源'); + return self::FAILURE; + } + $lock = Cache::lock('courier-unshipped-sync', 2100); + if (!$lock->get()) { + $this->warn('未发出明细正在同步,本次跳过。'); + return self::SUCCESS; + } + $failed = false; + try { + $returnedOk = true; + if (!$this->option('skip-returned') && ($selected === '' || str_starts_with($selected, 'intercept_'))) { + $returnedOk = $this->call('business-mirror:sync-returned-parcels') === self::SUCCESS; + } + foreach (UnshippedWaybills::SYNC_SOURCES as $source => $label) { + if ($selected !== '' && $selected !== $source) continue; + try { + if ($source === 'warehouse') { + $result = $sources->warehouse(max(0, (int) $this->option('max-batches')), + fn ($n, $last, $high) => $this->line("仓内未发:已扫描 {$n} 行,游标 {$last}/{$high}")); + if ($result['status'] === 'running') { + $this->line('仓内未发:分批同步进行中,保留上次完整结果。'); + continue; + } + $ok = true; + } elseif (str_starts_with($source, 'intercept_')) { + if (!$returnedOk) throw new \RuntimeException('退回件刷新失败,保留上次未发出结果。'); + $sources->intercept($source); + $ok = true; + } else { + $ok = $waybills->sync($source); + } + } catch (Throwable $error) { + report($error); + $ok = false; + $safeMessages = ['退回件明细尚未完成刷新,保留上次结果。', '退回件来源覆盖不足,保留上次结果。', '退回件刷新失败,保留上次未发出结果。']; + $warning = in_array($error->getMessage(), $safeMessages, true) ? $error->getMessage() : '来源读取失败,保留上次完整结果。'; + $waybills->connection()->table('courier_unshipped_sync')->updateOrInsert(['source' => $source], ['warning' => $warning]); + } + if (!$ok) { + $warning = $waybills->connection()->table('courier_unshipped_sync')->where('source', $source)->value('warning'); + $this->warn($label.':'.$warning); + $failed = true; + } else { + $state = $waybills->connection()->table('courier_unshipped_sync')->where('source', $source)->first(); + $this->info($label.':'.$state->row_count.' 行,缺单号 '.$state->missing_count.' 行。'); + } + } + return $failed ? self::FAILURE : self::SUCCESS; + } finally { + $lock->release(); } - - return $failed ? self::FAILURE : self::SUCCESS; } } diff --git a/app/Http/Controllers/Business/ReturnedParcelController.php b/app/Http/Controllers/Business/ReturnedParcelController.php index 39415995e..e12933775 100644 --- a/app/Http/Controllers/Business/ReturnedParcelController.php +++ b/app/Http/Controllers/Business/ReturnedParcelController.php @@ -19,7 +19,7 @@ class ReturnedParcelController extends Controller 'product_name' => '商品名称', 'properties' => '颜色规格', 'applied_qty' => '申请数量', 'returned_qty' => '实退数量', 'price' => '商品单价', 'item_amount' => '明细金额', 'status' => '售后状态', 'type' => '售后类型', 'goods_status' => '货物状态', 'reason' => '问题类型', - 'remark' => '备注', 'source_id' => '源明细编号', + 'remark' => '备注', 'source_kind' => '数据来源', 'source_id' => '源明细编号', ]; public function page(Request $request): array @@ -34,8 +34,9 @@ class ReturnedParcelController extends Controller return $data; } $query = $this->query($filters); - $data['summary'] = (clone $query)->selectRaw('COUNT(*) AS rows_count, COUNT(DISTINCT after_sales_id) AS orders_count, COALESCE(SUM(returned_qty),0) AS quantity')->first(); - $data['rows'] = $query->orderByDesc('received_at')->orderByDesc('source_id')->paginate(50)->withQueryString(); + $data['summary'] = (clone $query)->selectRaw('COUNT(*) AS rows_count, COALESCE(SUM(returned_qty),0) AS quantity')->first(); + $data['summary']->orders_count = $db->query()->fromSub((clone $query)->select(['source_kind', 'after_sales_id'])->distinct(), 'returned_orders')->count(); + $data['rows'] = $query->orderByDesc('received_at')->orderByDesc('source_kind')->orderByDesc('source_id')->paginate(50)->withQueryString(); $data['state'] = $db->table('business_mirror_table_states')->where('dataset_key', Sync::DATASET)->first(); } catch (Throwable $exception) { report($exception); @@ -53,9 +54,9 @@ class ReturnedParcelController extends Controller $file = fopen('php://output', 'w'); fwrite($file, "\xEF\xBB\xBF"); fputcsv($file, array_map(fn ($key) => self::COLUMNS[$key], $selected)); - foreach ($query->orderBy('source_id')->lazyById(1000, 'source_id') as $row) { + foreach (['regular', 'taobao'] as $source) foreach ((clone $query)->where('source_kind', $source)->orderBy('source_id')->lazyById(1000, 'source_id') as $row) { fputcsv($file, array_map(function ($key) use ($row) { - $value = (string) ($row->$key ?? ''); + $value = $key === 'source_kind' ? ($row->$key === 'taobao' ? '淘系' : '普通') : (string) ($row->$key ?? ''); if ($value !== '' && in_array($key, ['after_sales_id','online_after_sales_no','waybill','order_id','online_order_no','sku','style_code','source_id'], true)) return "'" . $value; return preg_match('/^[=+@\-\t\r]/u', $value) ? "'" . $value : $value; }, $selected)); diff --git a/app/Support/UnshippedSourceSynchronizer.php b/app/Support/UnshippedSourceSynchronizer.php new file mode 100644 index 000000000..516e86dd9 --- /dev/null +++ b/app/Support/UnshippedSourceSynchronizer.php @@ -0,0 +1,136 @@ +waybills->connection(); + $state = $db->table('business_mirror_table_states')->where('dataset_key', ReturnedParcelSynchronizer::DATASET)->first(); + if (!$state || $state->status !== 'succeeded' || !$state->last_succeeded_at) throw new RuntimeException('退回件明细尚未完成刷新,保留上次结果。'); + $history = $this->waybills->results()->where('source', 'intercept')->where('evidence_no', 'like', 'history:%')->max('evidence_time'); + $from = $history ? substr($history, 0, 10) : UnshippedWaybills::START; + if (substr((string)$state->window_started_at, 0, 10) > $from) throw new RuntimeException('退回件来源覆盖不足,保留上次结果。'); + $kind = $source === 'intercept_taobao' ? 'taobao' : 'regular'; + $generation = (string) Str::uuid(); $missing = 0; + $db->table('courier_unshipped_stage')->where('source', $source)->delete(); + $candidates = $db->table(ReturnedParcelSynchronizer::TABLE)->where('source_kind', $kind) + ->where('reason', UnshippedWaybills::SOURCES['intercept'])->where('received_at', '>=', $from) + ->selectRaw('after_sales_id,order_id,online_order_no,shop,MIN(received_at) AS received_at') + ->groupBy('after_sales_id','order_id','online_order_no','shop')->orderBy('after_sales_id'); + $candidates->chunk(100, function ($batch) use ($source, $generation, $kind, &$missing): void { + $ids = $batch->pluck('order_id')->filter(fn($id)=>ctype_digit((string)$id) && (int)$id > 0)->unique()->values()->all(); + $orders = $ids === [] ? [] : $this->originalOrders($kind, $ids); + $byOrder = []; + foreach ($orders as $order) { + $number = UnshippedWaybills::normalize($order['l_id'] ?? null); + if ($number !== '' && (!isset($byOrder[$order['o_id']]) || strcmp($number,$byOrder[$order['o_id']]['l_id'])<0)) $byOrder[$order['o_id']] = array_replace($order, ['l_id'=>$number]); + } + $rows = []; + foreach ($batch as $refund) { + $order = $byOrder[$refund->order_id] ?? null; + if (!$order) { $missing++; continue; } + $rows[] = ['source'=>$source,'waybill_no'=>UnshippedWaybills::normalize($order['l_id']), + 'evidence_no'=>(string)$refund->after_sales_id,'evidence_time'=>$refund->received_at, + 'courier_name'=>$order['logistics_company'],'o_id'=>$refund->order_id,'trade_no'=>$refund->online_order_no, + 'shop_name'=>$refund->shop,'evidence_text'=>UnshippedWaybills::SOURCES['intercept']]; + } + $this->stage($source,$generation,$rows); + }); + return $this->waybills->publishStage($source,$generation,$missing); + } + + protected function originalOrders(string $kind, array $ids): array + { + $table = $kind === 'taobao' ? 'jst_qmcust_orderlist' : 'jst_Orders'; + return $this->queries->forSourceWithTimeout('operations_replica',15)->select( + 'SELECT Id,o_id,l_id,logistics_company FROM rpt.'.$table.' WHERE o_id IN ('.implode(',',array_fill(0,count($ids),'CAST(? AS int)')).')',$ids); + } + + public function warehouse(int $maxBatches = 0, ?callable $progress = null): array + { + $db=$this->waybills->connection();$state=$db->table('business_mirror_table_states')->where('dataset_key',self::WAREHOUSE_DATASET)->first(); + $cursor=$state?json_decode($state->cursor??'null',true):null; + $resume=$state && in_array($state->status,['running','failed'],true) && is_array($cursor); + $generation=$resume?$state->generation:(string)Str::uuid();$last=$resume?(int)$cursor['last_id']:0; + $high=$resume?(int)$cursor['high_id']:$this->warehouseHighId();$scanned=$resume?(int)$cursor['scanned']:0; + if(!$resume)$db->table('courier_unshipped_stage')->where('source','warehouse')->delete(); + $db->table('business_mirror_table_states')->updateOrInsert(['dataset_key'=>self::WAREHOUSE_DATASET], + ['source_key'=>'operations_replica','source_object'=>'rpt.jst_workOrderInfo','target_table'=>'courier_unshipped_stage', + 'status'=>'running','run_mode'=>'full','generation'=>$generation,'last_attempted_at'=>now(),'updated_at'=>now(), + 'created_at'=>$state->created_at??now()]); + $batches=0; + try { + do { + $keys=$this->warehouseKeys($last,$high,5000); + if($keys===[])break; + $ids=[];foreach($keys as $key)if($key['woTypeId']===UnshippedWaybills::WAREHOUSE_WORK_TYPE)$ids[]=$key['Id']; + foreach(array_chunk($ids,100) as $part){ + $rows=[];foreach($this->warehouseDetails($part) as $order){ + if(substr($order['created'],0,10)'warehouse','waybill_no'=>$number,'evidence_no'=>$order['woNo'],'evidence_time'=>$order['created'], + 'o_id'=>$fields['o_id']??null,'courier_name'=>$fields['logisticsField']??null,'evidence_text'=>trim($order['status'].' '.$order['title'])]; + } + $this->stage('warehouse',$generation,$rows); + } + $next=(int)end($keys)['Id']; + if ($next <= $last) throw new RuntimeException('warehouse_cursor_not_advanced'); + $last=$next;$scanned+=count($keys);$batches++; + $db->table('business_mirror_table_states')->where('dataset_key',self::WAREHOUSE_DATASET)->update([ + 'cursor'=>json_encode(['last_id'=>$last,'high_id'=>$high,'scanned'=>$scanned]),'last_upserted_rows'=>$scanned,'updated_at'=>now()]); + $progress && $progress($scanned,$last,$high); + if($maxBatches>0 && $batches>=$maxBatches && $last<$high)return ['status'=>'running','scanned'=>$scanned]; + } while($last<$high); + $rows=$this->waybills->publishStage('warehouse',$generation,0); + $db->table('business_mirror_table_states')->where('dataset_key',self::WAREHOUSE_DATASET)->update([ + 'status'=>'succeeded','cursor'=>null,'initial_completed_at'=>now(),'last_succeeded_at'=>now(),'last_full_succeeded_at'=>now(), + 'mirror_row_count'=>$rows,'last_error_code'=>null,'updated_at'=>now()]); + return ['status'=>'succeeded','scanned'=>$scanned,'rows'=>$rows]; + }catch(Throwable $e){$db->table('business_mirror_table_states')->where('dataset_key',self::WAREHOUSE_DATASET)->update(['status'=>'failed','last_error_code'=>$e::class,'updated_at'=>now()]);throw $e;} + } + + protected function warehouseHighId(): int + { + return (int)$this->queries->forSourceWithTimeout('operations_replica',15)->scalar('SELECT MAX(Id) FROM rpt.jst_workOrderInfo'); + } + + protected function warehouseKeys(int $last,int $high,int $limit): array + { + return $this->queries->forSourceWithTimeout('operations_replica',15)->select('SELECT TOP ('.$limit.') Id,woTypeId FROM rpt.jst_workOrderInfo WHERE Id > ? AND Id <= ? ORDER BY Id',[$last,$high]); + } + + protected function warehouseDetails(array $ids): array + { + return $this->queries->forSourceWithTimeout('operations_replica',15)->select('SELECT Id,woNo,created,status,title,businessFieldList FROM rpt.jst_workOrderInfo WHERE Id IN ('.implode(',',array_fill(0,count($ids),'CAST(? AS int)')).')',$ids); + } + + private function stage(string $source,string $generation,array $rows): void + { + if($rows===[])return; + if ($source === 'warehouse') { + $numbers = array_column(array_filter($rows, fn ($row) => empty($row['courier_name'])), 'waybill_no'); + $couriers = $numbers === [] ? [] : $this->waybills->connection()->table('jst_oms_shipping')->whereIn('express_no', $numbers) + ->orderBy('id')->pluck('express_name1', 'express_no')->all(); + foreach ($rows as &$row) $row['courier_name'] = $row['courier_name'] ?: ($couriers[$row['waybill_no']] ?? null); + unset($row); + } + $values=[];foreach($rows as $r)$values[]=$r+['generation'=>$generation,'row_key'=>hash('sha256',$r['evidence_no'].'|'.$r['waybill_no']), + 'courier_name'=>null,'trade_no'=>null,'o_id'=>null,'shop_name'=>null,'new_courier_name'=>null,'new_waybill_no'=>null,'operator'=>null,'evidence_text'=>null]; + DB::connection('business_mirror')->table('courier_unshipped_stage')->upsert($values,['source','row_key'],array_keys($values[0])); + } +} diff --git a/app/Support/UnshippedWaybills.php b/app/Support/UnshippedWaybills.php index bef3d1ac9..cd1e7e963 100644 --- a/app/Support/UnshippedWaybills.php +++ b/app/Support/UnshippedWaybills.php @@ -12,8 +12,8 @@ final class UnshippedWaybills public const HISTORY_PREFIX = 'history:'; public const SOURCES = ['intercept' => '现场拦截入库签收', 'replacement' => '换单未发出', 'warehouse' => '仓内未发']; - private const WAREHOUSE_WORK_TYPE = '78FC156B524645E886F21A32ED67133F'; - private const WAREHOUSE_EXCLUDED_STATUSES = [ + public const WAREHOUSE_WORK_TYPE = '78FC156B524645E886F21A32ED67133F'; + public const WAREHOUSE_EXCLUDED_STATUSES = [ 'REJECT_AUDIT', 'DISABLED', 'REJECTED', 'REFUSED', 'CANCELED', 'CANCELLED', '已拒绝', '已取消', ]; @@ -100,7 +100,7 @@ final class UnshippedWaybills $cutoff = (clone $history)->max('evidence_time'); if ($cutoff !== null) { $covered = array_fill_keys((clone $history)->pluck('waybill_no')->all(), true); - $rows = array_filter($rows, fn ($row) => substr($row['evidence_time'], 0, 10) > substr($cutoff, 0, 10) + $rows = array_filter($rows, fn ($row) => (str_starts_with($row['evidence_no'], 'shipping:') || substr($row['evidence_time'], 0, 10) > substr($cutoff, 0, 10)) && !isset($covered[$row['waybill_no']])); } $db->transaction(function () use ($db, $source, $rows, $missing): void { @@ -119,7 +119,7 @@ final class UnshippedWaybills return true; } catch (Throwable $error) { - if (!$error instanceof RuntimeException || !in_array($error->getMessage(), ['未导入订单操作日志。', '未找到仓内未发工单类型或单号字段。', '依赖镜像暂无数据。', '依赖镜像尚未完成同步。'], true)) { + if (!$error instanceof RuntimeException || !in_array($error->getMessage(), ['未导入订单操作日志。', '尚无订单操作日志或发货换单记录。', '未找到仓内未发工单类型或单号字段。', '依赖镜像暂无数据。', '依赖镜像尚未完成同步。'], true)) { report($error); $warning = '读取失败,保留上次同步结果。'; } else { @@ -204,11 +204,56 @@ final class UnshippedWaybills 'new_courier_name' => $log->new_courier, 'new_waybill_no' => $log->new_waybill, ]; } - if ($currentOrder === null) throw new RuntimeException('未导入订单操作日志。'); + // 发货同步已明确保留的换单前单号也是证据;不是用订单商品或当前单号推断换单。 + if ($this->connection()->getSchemaBuilder()->hasColumn('jst_oms_shipping', 'front_no')) { + $ships = $this->connection()->table('jst_oms_shipping')->where('ship_time', '>=', self::START) + ->whereNotNull('front_no')->where('front_no', '<>', '')->whereColumn('front_no', '<>', 'express_no') + ->select(['id', 'source_id', 'front_no', 'express_no', 'trade_no', 'ship_time', 'express_name1'])->lazyById(500); + foreach ($ships as $ship) { + $old = self::normalize($ship->front_no); $new = self::normalize($ship->express_no); + if ($old === '' || $new === '' || $old === $new) continue; + // 旧号码仍是现有发货包裹时,不因另一条换单记录把它排除。 + if ($this->connection()->table('jst_oms_shipping')->whereIn('express_no', [$old, '@'.$old])->exists()) continue; + $rows['shipping:'.$ship->source_id.'|'.$old] = [ + 'source' => 'replacement', 'waybill_no' => $old, 'courier_name' => null, + 'evidence_no' => 'shipping:'.$ship->source_id, 'trade_no' => $ship->trade_no, + 'evidence_time' => $ship->ship_time, 'new_courier_name' => $ship->express_name1, + 'new_waybill_no' => $new, 'evidence_text' => '发货镜像明确记录换单前单号;依据时间为发货时间,非换单操作时间', + ]; + } + } + if ($currentOrder === null && $rows === []) throw new RuntimeException('尚无订单操作日志或发货换单记录。'); return [$rows, 0]; } + /** 完整批次才发布;失败/中断保留上一版及历史导入。 */ + public function publishStage(string $source, string $generation, int $missing): int + { + $db = $this->connection(); + return $db->transaction(function () use ($db, $source, $generation, $missing): int { + $historySource = in_array($source, ['intercept_regular', 'intercept_taobao'], true) ? 'intercept' : $source; + $history = $this->results()->where('source', $historySource)->where('evidence_no', 'like', self::HISTORY_PREFIX.'%'); + $cutoff = (clone $history)->max('evidence_time'); + $covered = array_fill_keys((clone $history)->pluck('waybill_no')->all(), true); + $this->results()->where('source', $source)->where('evidence_no', 'not like', self::HISTORY_PREFIX.'%')->delete(); + $count = 0; + $db->table('courier_unshipped_stage')->where('source', $source)->where('generation', $generation) + ->orderBy('row_key')->chunkById(300, function ($batch) use ($cutoff, $covered, &$count): void { + $rows = []; + foreach ($batch as $row) { + if ($cutoff !== null && (substr($row->evidence_time, 0, 10) <= substr($cutoff, 0, 10) || isset($covered[$row->waybill_no]))) continue; + $values = (array) $row; unset($values['generation'], $values['row_key']); $rows[] = $values; + } + if ($rows !== []) { $this->results()->insert($rows); $count += count($rows); } + }, 'row_key'); + $db->table('courier_unshipped_sync')->updateOrInsert(['source' => $source], [ + 'last_success_at' => now(), 'row_count' => $count, 'missing_count' => $missing, 'warning' => null, + ]); + return $count; + }); + } + private function warehouse(): array { $db = $this->connection(); diff --git a/database/migrations/2026_12_06_070000_create_unshipped_sync_stage.php b/database/migrations/2026_12_06_070000_create_unshipped_sync_stage.php new file mode 100644 index 000000000..af85c3ea8 --- /dev/null +++ b/database/migrations/2026_12_06_070000_create_unshipped_sync_stage.php @@ -0,0 +1,30 @@ +environment('testing') && config('system_database.mode', 'bootstrap') === 'bootstrap') return; + if (Schema::connection('business_mirror')->hasTable('courier_unshipped_stage')) return; + Schema::connection('business_mirror')->create('courier_unshipped_stage', function (Blueprint $table): void { + $table->string('source', 32); + $table->char('row_key', 64); + $table->uuid('generation'); + $table->string('waybill_no', 96); + $table->string('evidence_no', 96); + $table->dateTime('evidence_time'); + foreach (['courier_name', 'trade_no', 'o_id', 'shop_name', 'new_courier_name', 'new_waybill_no', 'operator'] as $field) $table->string($field)->nullable(); + $table->text('evidence_text')->nullable(); + $table->primary(['source', 'row_key']); + $table->index(['source', 'generation']); + }); + } + + public function down(): void + { + Schema::connection('business_mirror')->dropIfExists('courier_unshipped_stage'); + } +}; diff --git a/database/migrations/2026_12_06_070100_add_returned_parcel_source.php b/database/migrations/2026_12_06_070100_add_returned_parcel_source.php new file mode 100644 index 000000000..1298ab095 --- /dev/null +++ b/database/migrations/2026_12_06_070100_add_returned_parcel_source.php @@ -0,0 +1,47 @@ +environment('testing') && config('system_database.mode', 'bootstrap') === 'bootstrap') return; + $schema = Schema::connection('business_mirror'); + foreach (['courier_returned_parcels', 'courier_returned_parcels_stage'] as $name) { + if (! $schema->hasTable($name)) continue; + if (! $schema->hasColumn($name, 'source_kind')) { + $schema->table($name, fn (Blueprint $table) => $table->string('source_kind', 16)->default('regular')); + } + $connection = $schema->getConnection(); + $primary = collect($schema->getIndexes($name))->firstWhere('primary', true); + if (($primary['columns'] ?? []) !== ['source_kind', 'source_id']) { + if ($connection->getDriverName() === 'sqlite') { + // Laravel 10 does not compile primary-key changes for SQLite. + $manager = $connection->getDoctrineSchemaManager(); + $before = $manager->introspectTable($connection->getTablePrefix().$name); + $after = clone $before; + $after->dropPrimaryKey(); + $after->getColumn('source_id')->setAutoincrement(false); + $after->setPrimaryKey(['source_kind', 'source_id']); + $manager->alterTable($manager->createComparator()->compareTables($before, $after)); + } else { + $schema->table($name, function (Blueprint $table): void { + $table->dropPrimary(); + $table->primary(['source_kind', 'source_id']); + }); + } + } + $index = 'returned_source_date_'.(str_ends_with($name, '_stage') ? 'stage' : 'live'); + if (! collect($schema->getIndexes($name))->contains('name', $index)) { + $schema->table($name, fn (Blueprint $table) => $table->index(['received_at', 'source_kind', 'source_id'], $index)); + } + } + } + + public function down(): void + { + // 两个来源可能有相同编号,不能回滚成单编号主键并丢弃已同步明细。 + } +}; diff --git a/deploy/activate-incremental-release.sh b/deploy/activate-incremental-release.sh index c8571f707..89ddad128 100644 --- a/deploy/activate-incremental-release.sh +++ b/deploy/activate-incremental-release.sh @@ -233,7 +233,7 @@ CRON_TZ=Asia/Shanghai # 商品月加权与成本:先算月加权单价,再同步商品成本,避免成本先于价格生成。 0 18 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh finance:monthly-weighted-product-cost:auto >/dev/null 2>&1 # 店铺违规信息预警:每天 05:30 把副本库抓取结果追平到统一表(本地补充字段不覆盖)。 -10 5 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh courier:sync-unshipped-waybills --quiet >/dev/null 2>&1 +10 7 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh courier:sync-unshipped-waybills >>/opt/caiwuxitong/runtime/unshipped-sync.log 2>&1 30 5 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan store-violations:sync --quiet >/dev/null 2>&1 # 顾家发货明细:每天补齐货号到物料编号的唯一映射;无唯一命中时保留空值。 50 5 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-kuka-posting-material-map --quiet >/dev/null 2>&1 diff --git a/deploy/activate-release.sh b/deploy/activate-release.sh index ca9f33636..9f6e72eb8 100644 --- a/deploy/activate-release.sh +++ b/deploy/activate-release.sh @@ -237,7 +237,7 @@ CRON_TZ=Asia/Shanghai # 商品月加权与成本:先算月加权单价,再同步商品成本,避免成本先于价格生成。 0 18 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh finance:monthly-weighted-product-cost:auto >/dev/null 2>&1 # 店铺违规信息预警:每天 05:30 把副本库抓取结果追平到统一表(本地补充字段不覆盖)。 -10 5 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh courier:sync-unshipped-waybills --quiet >/dev/null 2>&1 +10 7 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh courier:sync-unshipped-waybills >>/opt/caiwuxitong/runtime/unshipped-sync.log 2>&1 30 5 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan store-violations:sync --quiet >/dev/null 2>&1 # 顾家发货明细:每天补齐货号到物料编号的唯一映射;无唯一命中时保留空值。 50 5 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-kuka-posting-material-map --quiet >/dev/null 2>&1 diff --git a/deploy/run-finance-batch.sh b/deploy/run-finance-batch.sh index 0d8bb65e9..b010e5087 100644 --- a/deploy/run-finance-batch.sh +++ b/deploy/run-finance-batch.sh @@ -153,7 +153,7 @@ if [ "$1" = 'account-mapping:refresh-coverage' ]; then --name "$container_name" batch "$@" exit $? fi -if [ "$1" = 'business-mirror:sync-returned-parcels' ] || [ "$1" = 'courier-surcharge:pull-customer-service' ]; then +if [ "$1" = 'business-mirror:sync-returned-parcels' ] || [ "$1" = 'courier:sync-unshipped-waybills' ] || [ "$1" = 'courier-surcharge:pull-customer-service' ]; then container_name="caiwu_returned_parcels_$$" cleanup_returned_parcels() { docker rm --force "$container_name" >/dev/null 2>&1 || true diff --git a/docs/上游业务镜像清单.md b/docs/上游业务镜像清单.md index 75e71558d..b070c12d8 100644 --- a/docs/上游业务镜像清单.md +++ b/docs/上游业务镜像清单.md @@ -32,9 +32,11 @@ ## 当前迁移状态 -“快递应付 → 退回件明细”按 `operations_replica/rpt.jst_returnAndRefundItem.receive_date`(进仓时间)读取 2026-10-01 起的商品明细,并按 `as_id` 关联 `rpt.jst_returnAndRefundInfo` 的售后、快递、店铺和仓库字段。结果写入共享镜像 `courier_returned_parcels`,源明细 `Id` 为稳定键;分批结果先写 `courier_returned_parcels_stage`,复用 `business_mirror_table_states` 保存游标。完整核对来源计数后在事务内替换指定进仓日期范围,失败保留上次完整结果,相同日期重跑可续传。页面只读此镜像,支持分页、精确筛选和流式 CSV 导出。首次指定 `--from=2026-10-01 --to=2026-12-02`(两端包含),日常从 2026-10-01 校准到当天,以覆盖退货明细无可靠更新时间造成的迟到与历史修订。 +“快递应付 → 退回件明细”同时读取 `operations_replica/rpt.jst_returnAndRefundItem`(普通)与 `rpt.jst_qmcust_refundlist_item`(淘系),按 `receive_date`(进仓时间)读取 2026-10-01 起的商品明细,并按 `as_id` 分别关联 `rpt.jst_returnAndRefundInfo`、`rpt.jst_qmcust_refundlist` 的售后、快递、店铺和仓库字段。结果写入共享镜像 `courier_returned_parcels`,`source_kind + source_id` 为稳定键(普通取 `Id`,淘系取 `asi_id`);两来源允许编号相同。分批结果先写 `courier_returned_parcels_stage`,复用 `business_mirror_table_states` 保存来源及游标。分别完整核对两来源计数后在事务内替换指定进仓日期范围,失败保留上次完整结果,相同日期重跑可续传。页面只读此镜像,支持分页、精确筛选和流式 CSV 导出。首次指定 `--from=2026-10-01 --to=2026-12-02`(两端包含),日常从 2026-10-01 校准到当天,以覆盖退货明细无可靠更新时间造成的迟到与历史修订。 -生产入口:`sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-returned-parcels`,北京时间每天 10:00、16:00 执行。沿用全局上游锁和独立批容器(1 CPU、3 GiB、PHP 512 MiB),单次容器执行上限 30 分钟、单条上游查询上限 60 秒;每批最多 2,000 条商品,按所选商品关联售后主表。命令不会写聚水潭或其他财务台账。 +生产入口:`sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-returned-parcels`,北京时间每天 10:00、16:00 执行。沿用全局上游锁和独立批容器(1 CPU、3 GiB、PHP 512 MiB),单次容器执行上限 30 分钟、单条上游查询上限 60 秒;每轮先读取至多 5,000 个稳定编号和进仓时间,最多取 2,000 条符合日期的商品,按 500 个编号读取明细、100 个售后号关联主表。命令不会写聚水潭或其他财务台账。 + +“未发出明细”每日 07:10 通过 `courier:sync-unshipped-waybills` 在同一受限批入口刷新。先完成上述退回件快照,再分别获取普通、淘系现场拦截的原订单发出单号;不因其他全量退款镜像失败而阻断。仓内未发从当前 `operations_replica/rpt.jst_workOrderInfo` 按 `Id` 每批读取 5,000 个类型索引,再按匹配类型的明确 ID 读取业务字段;不恢复退役 `jiansun` 连接。派生暂存 `courier_unshipped_stage` 及数据集 `derived.courier-unshipped-warehouse` 保留断点,完整后才发布,历史导入保留。`--max-batches` 可控制单轮批数,`--source` 可指定来源,刚完成退回件校准时可用 `--skip-returned`。换单除人工操作日志外,还读取发货镜像明确记录的 `front_no`;该依据时间是发货时间,不冒充换单操作时间,也不把国际物流号当旧单号。无历史导入且退回件覆盖不足时拒绝发布拦截结果,避免把不完整范围当全量。 | 状态 | 说明 | | --- | --- | diff --git a/modules/EcommerceFinance/Services/ReturnedParcelSynchronizer.php b/modules/EcommerceFinance/Services/ReturnedParcelSynchronizer.php index 5cf59a84a..ea6ec4e3a 100644 --- a/modules/EcommerceFinance/Services/ReturnedParcelSynchronizer.php +++ b/modules/EcommerceFinance/Services/ReturnedParcelSynchronizer.php @@ -11,6 +11,9 @@ use Throwable; /** 按进仓时间同步商品级退回件;分页落暂存表,完整校验后才发布新快照。 */ class ReturnedParcelSynchronizer { + protected string $sourceKind = 'regular'; + protected ?int $scannedThrough = null; + protected bool $sourceExhausted = false; public const DATASET = 'derived.courier-returned-parcels'; public const START = '2026-10-01'; public const TABLE = 'courier_returned_parcels'; @@ -25,12 +28,14 @@ class ReturnedParcelSynchronizer $state = $db->table('business_mirror_table_states')->where('dataset_key', self::DATASET)->first(); $cursor = $state ? json_decode($state->cursor ?? 'null', true) : null; $resume = $state && in_array($state->status, ['running', 'failed'], true) - && is_array($cursor) && ($cursor['from'] ?? null) === $from && ($cursor['to'] ?? null) === $to; + && is_array($cursor) && ($cursor['from'] ?? null) === $from && ($cursor['to'] ?? null) === $to + && ($cursor['version'] ?? 0) === 2; $generation = $resume ? $state->generation : (string) Str::uuid(); $last = $resume ? (int) $cursor['last_id'] : 0; + $resumeSource = $resume ? ($cursor['source'] ?? 'regular') : 'regular'; $batchSize = min(max($batchSize, 1), 2000); $started = microtime(true); - $base = ['source_key' => 'operations_replica', 'source_object' => 'rpt.jst_returnAndRefundInfo + rpt.jst_returnAndRefundItem', + $base = ['source_key' => 'operations_replica', 'source_object' => 'rpt.jst_returnAndRefundInfo/Item + rpt.jst_qmcust_refundlist/Item', 'target_table' => self::TABLE, 'status' => 'running', 'run_mode' => 'full', 'generation' => $generation, 'last_attempted_at' => now(), 'last_error_code' => null, 'updated_at' => now()]; $db->table('business_mirror_table_states')->updateOrInsert(['dataset_key' => self::DATASET], $base + @@ -38,35 +43,53 @@ class ReturnedParcelSynchronizer try { if (! $resume) $db->table(self::STAGE)->delete(); - $expected = $this->sourceCount($from, $until); - while (true) { + $expected = 0; $expectedBySource = []; + foreach ($this->sources() as $source) { + $this->sourceKind = $source; + $expectedBySource[$source] = $this->sourceCount($from, $until); + $expected += $expectedBySource[$source]; + } + foreach ($this->sources() as $source) { + $this->sourceKind = $source; + if ($resume && $source === 'regular' && $resumeSource === 'taobao') continue; + if (! $resume || $source !== $resumeSource) $last = 0; + while (true) { + $this->scannedThrough = null; + $this->sourceExhausted = false; $items = $this->items($from, $until, $last, $batchSize); - if ($items === []) break; - $headers = $this->headers(array_values(array_unique(array_column($items, 'as_id')))); + if ($items === [] && $this->scannedThrough === null) break; + $headers = $items === [] ? [] : $this->headers(array_values(array_unique(array_column($items, 'as_id')))); $rows = []; foreach ($items as $item) { $header = $headers[(string) $item['as_id']] ?? null; if ($header === null) throw new RuntimeException('missing_after_sales_header'); $rows[] = $this->row($item, $header, $generation); } - $last = (int) end($items)['Id']; + $next = $this->scannedThrough ?? (int) end($items)['Id']; + if ($next <= $last) throw new RuntimeException('source_cursor_not_advanced'); + $last = $next; $db->transaction(function () use ($db, $rows, $last, $generation, $from, $to): void { foreach (array_chunk($rows, 400) as $part) { - $db->table(self::STAGE)->upsert($part, ['source_id'], array_keys($part[0])); + $db->table(self::STAGE)->upsert($part, ['source_kind', 'source_id'], array_keys($part[0])); } $db->table('business_mirror_table_states')->where('dataset_key', self::DATASET)->update([ - 'cursor' => json_encode(['from' => $from, 'to' => $to, 'last_id' => $last]), + 'cursor' => json_encode(['version' => 2, 'source' => $this->sourceKind, 'from' => $from, 'to' => $to, 'last_id' => $last]), 'last_upserted_rows' => $db->table(self::STAGE)->where('generation', $generation)->count(), 'updated_at' => now(), ]); }); $progress && $progress($db->table(self::STAGE)->where('generation', $generation)->count(), $expected); - if (count($items) < $batchSize) break; + if ($this->sourceExhausted || ($this->scannedThrough === null && count($items) < $batchSize)) break; + } } $count = $db->table(self::STAGE)->where('generation', $generation)->count(); - if ($count !== $expected || $count !== $this->sourceCount($from, $until)) { - $db->table('business_mirror_table_states')->where('dataset_key', self::DATASET)->update(['cursor' => null]); - throw new RuntimeException('source_count_changed_retry_required'); + foreach ($this->sources() as $source) { + $this->sourceKind = $source; + $staged = $db->table(self::STAGE)->where('generation', $generation)->where('source_kind', $source)->count(); + if ($staged !== $expectedBySource[$source] || $staged !== $this->sourceCount($from, $until)) { + $db->table('business_mirror_table_states')->where('dataset_key', self::DATASET)->update(['cursor' => null]); + throw new RuntimeException('source_count_changed_retry_required'); + } } // 同一事务替换范围,失败或中断不影响页面上一版;只操作派生镜像。 $db->transaction(function () use ($db, $from, $until, $generation, $count): void { @@ -83,7 +106,7 @@ class ReturnedParcelSynchronizer $db->table(self::STAGE)->where('generation', $generation)->delete(); }); return ['rows' => $count, 'from' => $from, 'to' => $to, 'seconds' => round(microtime(true) - $started, 2), - 'peak_mb' => round(memory_get_peak_usage(true) / 1048576, 2)]; + 'peak_mb' => round(memory_get_peak_usage(true) / 1048576, 2), 'sources' => $expectedBySource]; } catch (Throwable $exception) { $db->table('business_mirror_table_states')->where('dataset_key', self::DATASET)->update([ 'status' => 'failed', 'last_error_code' => class_basename($exception), 'updated_at' => now(), @@ -94,21 +117,40 @@ class ReturnedParcelSynchronizer protected function sourceCount(string $from, string $until): int { - return (int) $this->upstream()->scalar('SELECT COUNT_BIG(*) FROM rpt.jst_returnAndRefundItem WHERE receive_date >= CAST(? AS datetime) AND receive_date < CAST(? AS datetime)', [$from, $until]); + return (int) $this->upstream()->scalar('SELECT COUNT_BIG(*) FROM rpt.'.$this->itemTable().' WHERE receive_date >= CAST(? AS datetime) AND receive_date < CAST(? AS datetime)', [$from, $until]); } protected function items(string $from, string $until, int $last, int $limit): array { - return $this->upstream()->select('SELECT TOP (' . $limit . ') Id,as_id,asi_id,CONVERT(varchar(27),receive_date,126) AS receive_date,' - . 'sku_id,i_id,name,properties_value,qty,r_qty,price,amount,remark FROM rpt.jst_returnAndRefundItem' - . ' WHERE receive_date >= CAST(? AS datetime) AND receive_date < CAST(? AS datetime) AND Id > ? ORDER BY Id', [$from, $until, $last]); + $key = $this->sourceKind === 'taobao' ? 'asi_id' : 'Id'; + // 日期过滤加宽字段会使副本视图选择全表排序。先只读稳定键和日期,再按明确键取明细。 + $keys = $this->upstream()->select('SELECT TOP (5000) '.$key.' AS Id,CONVERT(varchar(27),receive_date,126) AS receive_date' + .' FROM rpt.'.$this->itemTable().' WHERE '.$key.' > CAST(? AS int) ORDER BY '.$key, [$last]); + if ($keys === []) { $this->sourceExhausted = true; return []; } + $ids = []; + foreach ($keys as $row) { + $this->scannedThrough = (int) $row['Id']; + if ($row['receive_date'] !== null && $row['receive_date'] >= $from && $row['receive_date'] < $until) $ids[] = $row['Id']; + if (count($ids) >= $limit) break; + } + $this->sourceExhausted = count($keys) < 5000 && $this->scannedThrough === (int) end($keys)['Id']; + $rows = []; + foreach (array_chunk($ids, 500) as $part) { + array_push($rows, ...$this->upstream()->select('SELECT '.$key.' AS Id,as_id,asi_id,CONVERT(varchar(27),receive_date,126) AS receive_date,' + .'sku_id,i_id,name,properties_value,qty,r_qty,price,amount,remark FROM rpt.'.$this->itemTable() + .' WHERE '.$key.' IN ('.implode(',', array_fill(0, count($part), 'CAST(? AS int)')).') ORDER BY '.$key, $part)); + } + return $rows; } protected function headers(array $ids): array { - $rows = $this->upstream()->select('SELECT Id,as_id,outer_as_id,o_id,so_id,l_id,logistics_company,shop_name,warehouse,' - . 'status,type,good_status,question_type,refund,remark,CONVERT(varchar(27),updateTime,126) AS updateTime' - . ' FROM rpt.jst_returnAndRefundInfo WHERE as_id IN (' . implode(',', array_fill(0, count($ids), '?')) . ')', $ids); + $taobao = $this->sourceKind === 'taobao'; + $rows = []; + foreach (array_chunk($ids, 100) as $part) array_push($rows, ...$this->upstream()->select('SELECT '.($taobao ? 'as_id AS Id' : 'Id').',as_id,outer_as_id,o_id,so_id,l_id,logistics_company,shop_name,warehouse,' + . 'status,type,good_status,question_type,refund,remark,CONVERT(varchar(27),'.($taobao ? 'local_updated' : 'updateTime').',126) AS updateTime' + . ' FROM rpt.'.($taobao ? 'jst_qmcust_refundlist' : 'jst_returnAndRefundInfo').' WHERE as_id IN (' + . implode(',', array_fill(0, count($part), $taobao ? 'CAST(? AS varchar(20))' : 'CAST(? AS bigint)')) . ')', $part)); $headers = []; foreach ($rows as $row) { $key = (string) $row['as_id']; @@ -122,9 +164,13 @@ class ReturnedParcelSynchronizer return $this->queries->forSourceWithTimeout('operations_replica', 60); } + protected function sources(): array { return ['regular', 'taobao']; } + + private function itemTable(): string { return $this->sourceKind === 'taobao' ? 'jst_qmcust_refundlist_item' : 'jst_returnAndRefundItem'; } + private function row(array $i, array $h, string $generation): array { - return ['source_id' => $i['Id'], 'after_sales_id' => $i['as_id'], 'item_id' => $i['asi_id'], + return ['source_kind' => $this->sourceKind, 'source_id' => $i['Id'], 'after_sales_id' => $i['as_id'], 'item_id' => $i['asi_id'], 'received_at' => $i['receive_date'], 'online_after_sales_no' => $h['outer_as_id'], 'order_id' => $h['o_id'], 'online_order_no' => $h['so_id'], 'waybill' => $h['l_id'], 'courier' => $h['logistics_company'], 'shop' => $h['shop_name'], 'warehouse' => $h['warehouse'], diff --git a/resources/views/business/pages/courier-payables/returned-parcels.blade.php b/resources/views/business/pages/courier-payables/returned-parcels.blade.php index e29af1036..a5b00802a 100644 --- a/resources/views/business/pages/courier-payables/returned-parcels.blade.php +++ b/resources/views/business/pages/courier-payables/returned-parcels.blade.php @@ -25,7 +25,8 @@ @forelse($rows ?? [] as $row) @foreach($columns as $key => $label) in_array($key,['applied_qty','returned_qty','price','item_amount'])])> - @if(in_array($key,['price','item_amount'])){{ $row->$key === null ? '—' : number_format($row->$key, 2) }} + @if($key === 'source_kind'){{ $row->$key === 'taobao' ? '淘系' : '普通' }} + @elseif(in_array($key,['price','item_amount'])){{ $row->$key === null ? '—' : number_format($row->$key, 2) }} @elseif(in_array($key,['applied_qty','returned_qty'])){{ $row->$key === null ? '—' : rtrim(rtrim(number_format($row->$key, 4, '.', ''), '0'), '.') }} @else{{ $row->$key ?? '—' }}@endif @@ -37,7 +38,7 @@ @if($rows)@endif -

按聚水潭进仓时间展示商品明细;同一售后单有多件商品或分批退回时可出现多行。筛选日期包含起止当天。

+

包含普通、淘系两套退货数据,按聚水潭进仓时间展示商品明细;同一售后单有多件商品或分批退回时可出现多行。筛选日期包含起止当天。