fix(同步): 补齐淘系退回件并恢复未发出明细刷新 #1780

Closed
limeng wants to merge 2 commits from fix/limeng-unshipped-sync-recovery into main
15 changed files with 568 additions and 57 deletions

View File

@ -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;
}
}

View File

@ -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));

View File

@ -0,0 +1,136 @@
<?php
namespace App\Support;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Modules\EcommerceFinance\Services\ReturnedParcelSynchronizer;
use Modules\EcommerceFinance\Services\UpstreamReadOnlyQueryFactory;
use RuntimeException;
use Throwable;
/** 未发出名单的受控刷新:先完成来源快照,再原子发布,网页不查询上游。 */
class UnshippedSourceSynchronizer
{
public const WAREHOUSE_DATASET = 'derived.courier-unshipped-warehouse';
public function __construct(private readonly UpstreamReadOnlyQueryFactory $queries, private readonly UnshippedWaybills $waybills) {}
public function intercept(string $source): int
{
$db = $this->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)<UnshippedWaybills::START || in_array($order['status'],UnshippedWaybills::WAREHOUSE_EXCLUDED_STATUSES,true))continue;
$fields=array_column(json_decode($order['businessFieldList'],true,512,JSON_THROW_ON_ERROR)?:[],'value','fieldId');
$number=UnshippedWaybills::normalize($fields['lIdField']??null);if($number==='')continue;
$rows[]=['source'=>'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]));
}
}

View File

@ -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();

View File

@ -0,0 +1,30 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
public function up(): void
{
if (! app()->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');
}
};

View File

@ -0,0 +1,47 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
public function up(): void
{
if (! app()->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
{
// 两个来源可能有相同编号,不能回滚成单编号主键并丢弃已同步明细。
}
};

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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`;该依据时间是发货时间,不冒充换单操作时间,也不把国际物流号当旧单号。无历史导入且退回件覆盖不足时拒绝发布拦截结果,避免把不完整范围当全量。
| 状态 | 说明 |
| --- | --- |

View File

@ -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'],

View File

@ -25,7 +25,8 @@
@forelse($rows ?? [] as $row)
<tr>@foreach($columns as $key => $label)
<td @class(['returned-number' => 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
</td>
@ -37,7 +38,7 @@
</table>
</div>
@if($rows)<div class="returned-parcels-footer" data-returned-pagination>每页 50 条 {{ $rows->links('business.partials.previous-next-pagination') }}</div>@endif
<p class="returned-parcels-note">按聚水潭进仓时间展示商品明细;同一售后单有多件商品或分批退回时可出现多行。筛选日期包含起止当天。</p>
<p class="returned-parcels-note">包含普通、淘系两套退货数据,按聚水潭进仓时间展示商品明细;同一售后单有多件商品或分批退回时可出现多行。筛选日期包含起止当天。</p>
</section>
<style>
.returned-parcels{color:var(--vip-content-ink,#171717);font-size:13px}.returned-parcels-filters{display:flex;flex-wrap:wrap;gap:12px;align-items:flex-end;margin-bottom:14px}.returned-parcels-filters label{display:grid;gap:6px;font-size:12px}.returned-parcels-filters input{width:160px}.returned-parcels-filters input,.returned-parcels-filters button,.returned-parcels-filters a{height:34px;border:1px solid var(--vip-border,#D8D2C7);border-radius:8px;padding:0 10px;background:white;color:inherit}.returned-parcels-filters a{display:inline-flex;align-items:center;text-decoration:none}.returned-parcels-filters .returned-primary{background:var(--vip-content-accent-dark,#856632);color:white;border-color:var(--vip-content-accent-dark,#856632)}.returned-parcels-filters input:focus{outline:2px solid var(--vip-content-accent,#B9954F);outline-offset:2px}.returned-parcels-status,.returned-parcels-note{color:var(--vip-content-muted,#595959);font-size:12px;margin:10px 0}.returned-warning{color:var(--vip-warning,#935F07)}.returned-parcels-summary{margin:14px 0}.returned-parcels-scroll{overflow:auto;max-height:calc(100vh - 360px);min-height:220px;border:1px solid var(--vip-border,#D8D2C7);border-radius:8px;background:white}.returned-parcels table{border-collapse:collapse;width:100%;font-size:12.5px}.returned-parcels th,.returned-parcels td{padding:10px 12px;border-bottom:1px solid var(--vip-border,#D8D2C7);text-align:left;white-space:nowrap;max-width:320px;overflow:hidden;text-overflow:ellipsis}.returned-parcels th{position:sticky;top:0;background:var(--vip-content-accent-soft,#F7F0DE);z-index:1;font-size:12px}.returned-parcels td.returned-number,.returned-parcels th.returned-number{text-align:right;font-variant-numeric:tabular-nums}.returned-parcels tbody tr:hover{background:var(--vip-content-accent-soft,#F7F0DE)}.returned-parcels td.returned-empty{text-align:center;padding:40px;white-space:normal}.returned-parcels-footer{display:flex;justify-content:space-between;align-items:center;margin-top:12px}.returned-parcels-footer nav{margin:0}

View File

@ -35,6 +35,7 @@ class ReturnedParcelsTest extends FeatureTestCase
if (! $schema->hasTable(ReturnedParcelSynchronizer::TABLE)) {
(require base_path('database/migrations/2026_12_03_200000_create_courier_returned_parcel_mirror.php'))->up();
}
(require base_path('database/migrations/2026_12_06_070100_add_returned_parcel_source.php'))->up();
}
private function synchronizer(array $items): ReturnedParcelFakeSynchronizer
@ -64,6 +65,22 @@ class ReturnedParcelsTest extends FeatureTestCase
$this->assertSame('TEST-RETURN', $rows[0]->waybill);
}
public function test_source_key_migration_keeps_existing_rows_and_can_resume(): void
{
$db = DB::connection('business_mirror');
foreach ([ReturnedParcelSynchronizer::TABLE, ReturnedParcelSynchronizer::STAGE] as $name) {
$db->getSchemaBuilder()->drop($name);
}
(require base_path('database/migrations/2026_12_03_200000_create_courier_returned_parcel_mirror.php'))->up();
$db->table(ReturnedParcelSynchronizer::TABLE)->insert(['source_id'=>9,'received_at'=>'2026-11-01','generation'=>'old','synced_at'=>now()]);
$migration = require base_path('database/migrations/2026_12_06_070100_add_returned_parcel_source.php');
$migration->up();
$migration->up();
$this->assertSame('regular', $db->table(ReturnedParcelSynchronizer::TABLE)->value('source_kind'));
$db->table(ReturnedParcelSynchronizer::TABLE)->insert(['source_kind'=>'taobao','source_id'=>9,'received_at'=>'2026-11-01','generation'=>'new','synced_at'=>now()]);
$this->assertSame(2,$db->table(ReturnedParcelSynchronizer::TABLE)->count());
}
public function test_failed_sync_keeps_live_rows_and_resumes_from_committed_batch(): void
{
$sync=$this->synchronizer([$this->item(10)]);
@ -95,6 +112,46 @@ class ReturnedParcelsTest extends FeatureTestCase
$this->assertNull($db->table('business_mirror_table_states')->value('cursor'));
}
public function test_empty_scan_window_saves_cursor_and_continues_to_matching_rows(): void
{
$sync = new class([$this->item(7000)]) extends ReturnedParcelFakeSynchronizer {
protected function items(string $from, string $until, int $last, int $limit): array
{
if ($last === 0) { $this->scannedThrough = 5000; return []; }
return parent::items($from, $until, $last, $limit);
}
};
$this->assertSame(1, $sync->sync('2026-10-01','2026-12-02')['rows']);
$this->assertSame(5000, $sync->readCursors[0]);
}
public function test_both_sources_keep_same_detail_number_and_export_every_row(): void
{
$sync=$this->synchronizer([]);
$sync->multipleSources=['regular'=>[$this->item(7)],'taobao'=>[$this->item(7),$this->item(8)]];
$result=$sync->sync('2026-10-01','2026-12-02',null,1);
$this->assertSame(['regular'=>1,'taobao'=>2],$result['sources']);
$db=DB::connection('business_mirror');
$this->assertSame(3,$db->table(ReturnedParcelSynchronizer::TABLE)->count());
$data=app(ReturnedParcelController::class)->page(Request::create('/?from=2026-11-01&to=2026-11-30'));
$this->assertSame(2,(int)$data['summary']->orders_count);
$response=app(ReturnedParcelController::class)->export(Request::create('/?columns=source_kind,source_id'));
ob_start();$response->sendContent();$csv=ob_get_clean();
$this->assertSame(4,count(array_filter(explode("\n",$csv))));
$this->assertStringContainsString('普通',$csv);$this->assertStringContainsString('淘系',$csv);
}
public function test_failure_in_second_source_does_not_publish_half_snapshot_and_can_resume(): void
{
$sync=$this->synchronizer([$this->item(1)]);$sync->sync('2026-10-01','2026-12-02');
$sync=$this->synchronizer([]);$sync->multipleSources=['regular'=>[$this->item(2)],'taobao'=>[$this->item(3),$this->item(4)]];
$sync->failSource='taobao';
try{$sync->sync('2026-10-01','2026-12-02',null,1);$this->fail('Expected failure');}catch(RuntimeException $e){$this->assertSame('upstream_failed',$e->getMessage());}
$db=DB::connection('business_mirror');$this->assertSame([1],$db->table(ReturnedParcelSynchronizer::TABLE)->pluck('source_id')->all());
$sync->failSource=null;$sync->sync('2026-10-01','2026-12-02',null,1);
$this->assertSame([2,3,4],$db->table(ReturnedParcelSynchronizer::TABLE)->orderBy('source_id')->pluck('source_id')->all());
}
public function test_page_reads_mirror_filters_received_date_and_paginates(): void
{
$items=[];
@ -162,19 +219,24 @@ class ReturnedParcelsTest extends FeatureTestCase
class ReturnedParcelFakeSynchronizer extends ReturnedParcelSynchronizer
{
public ?array $multipleSources=null;
public ?string $failSource=null;
protected function sources(): array { return $this->multipleSources===null?['regular']:array_keys($this->multipleSources); }
private function currentRows(): array { return $this->multipleSources[$this->sourceKind]??$this->source; }
public ?int $failAfter=null;
public int $countOffset=0;
public array $readCursors=[];
public function __construct(public array $source) {}
protected function sourceCount(string $from,string $until): int
{
return count(array_filter($this->source,fn($row)=>$row['receive_date'] >= $from && $row['receive_date'] < $until))+$this->countOffset;
return count(array_filter($this->currentRows(),fn($row)=>$row['receive_date'] >= $from && $row['receive_date'] < $until))+$this->countOffset;
}
protected function items(string $from,string $until,int $last,int $limit): array
{
$this->readCursors[]=$last;
if($this->sourceKind===$this->failSource)throw new RuntimeException('upstream_failed');
if($this->failAfter!==null && count($this->readCursors)>$this->failAfter)throw new RuntimeException('upstream_failed');
return array_slice(array_values(array_filter($this->source,fn($row)=>$row['Id']>$last && $row['receive_date'] >= $from && $row['receive_date'] < $until)),0,$limit);
return array_slice(array_values(array_filter($this->currentRows(),fn($row)=>$row['Id']>$last && $row['receive_date'] >= $from && $row['receive_date'] < $until)),0,$limit);
}
protected function headers(array $ids): array
{

View File

@ -0,0 +1,70 @@
<?php
namespace Tests\Feature\Business;
use App\Support\UnshippedSourceSynchronizer;
use App\Support\UnshippedWaybills;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Modules\EcommerceFinance\Services\ReturnedParcelSynchronizer;
use RuntimeException;
use Tests\Feature\FeatureTestCase;
class UnshippedSourceSynchronizerTest extends FeatureTestCase
{
protected function setUp(): void
{
parent::setUp();
$schema = Schema::connection('business_mirror');
$schema->create('business_mirror_table_states', function (Blueprint $table): void {
$table->string('dataset_key')->primary();
foreach (['source_key','source_object','target_table','status','run_mode','generation','last_error_code'] as $key) $table->string($key)->nullable();
$table->text('cursor')->nullable();
foreach (['window_started_at','window_ends_at','initial_completed_at','last_full_succeeded_at','last_attempted_at','last_succeeded_at'] as $key) $table->dateTime($key)->nullable();
$table->integer('last_upserted_rows')->default(0);
$table->integer('mirror_row_count')->default(0);
$table->timestamps();
});
(require base_path('database/migrations/2026_12_06_070100_add_returned_parcel_source.php'))->up();
}
public function test_warehouse_reads_current_source_and_only_publishes_complete_run(): void
{
$service=app(UnshippedWaybills::class);$sync=new FakeUnshippedSources($service);
$result=$sync->warehouse(1);
$this->assertSame('running',$result['status']);
$this->assertSame(0,$service->results()->count());
$result=$sync->warehouse();
$this->assertSame('succeeded',$result['status']);
$this->assertSame(['W1'], $service->results()->pluck('waybill_no')->all());
$this->assertSame(2, $result['scanned']);
}
public function test_intercept_uses_both_sources_and_original_order_waybill(): void
{
$service=app(UnshippedWaybills::class);$db=$service->connection();$sync=new FakeUnshippedSources($service);
$db->table('business_mirror_table_states')->insert(['dataset_key'=>ReturnedParcelSynchronizer::DATASET,'source_key'=>'operations_replica',
'source_object'=>'test','target_table'=>ReturnedParcelSynchronizer::TABLE,'status'=>'succeeded','last_succeeded_at'=>now(),
'window_started_at'=>'2026-09-01','created_at'=>now(),'updated_at'=>now()]);
foreach(['regular','taobao'] as $kind)$db->table(ReturnedParcelSynchronizer::TABLE)->insert([
'source_kind'=>$kind,'source_id'=>1,'after_sales_id'=>10,'order_id'=>'100','online_order_no'=>'TRADE',
'waybill'=>'RETURN','received_at'=>'2026-11-28','shop'=>'测试店','generation'=>'one','synced_at'=>now(),
'reason'=>'现场拦截入库签收']);
$this->assertSame(1,$sync->intercept('intercept_regular'));
$this->assertSame(1,$sync->intercept('intercept_taobao'));
$this->assertSame(['ORIGINAL'=>['现场拦截入库签收']],$service->unshippedSources(['ORIGINAL','RETURN']));
$db->table('business_mirror_table_states')->update(['status'=>'failed']);
$this->expectException(RuntimeException::class);$sync->intercept('intercept_regular');
}
}
class FakeUnshippedSources extends UnshippedSourceSynchronizer
{
public function __construct(UnshippedWaybills $waybills){parent::__construct(app(\Modules\EcommerceFinance\Services\UpstreamReadOnlyQueryFactory::class),$waybills);}
protected function warehouseHighId(): int{return 2;}
protected function warehouseKeys(int $last,int $high,int $limit): array{return $last<2?[['Id'=>$last+1,'woTypeId'=>UnshippedWaybills::WAREHOUSE_WORK_TYPE]]:[];}
protected function warehouseDetails(array $ids): array{return [['Id'=>$ids[0],'woNo'=>'GD'.$ids[0],'created'=>'2026-11-28','title'=>'测试工单',
'status'=>$ids[0]===1?'WAIT_AUDIT':'REJECT_AUDIT','businessFieldList'=>json_encode([['fieldId'=>'lIdField','value'=>'W'.$ids[0]]])]];}
protected function originalOrders(string $kind,array $ids): array{return [['Id'=>1,'o_id'=>'100','l_id'=>'ORIGINAL','logistics_company'=>'测试快递']];}
}

View File

@ -19,7 +19,7 @@ final class UnshippedWaybillsTest extends FeatureTestCase
$this->assertNull(UnshippedWaybills::parseRemark('德邦:7.91508E+13->德邦:DPK002'));
$this->assertNull(UnshippedWaybills::parseRemark('没有新单号'));
foreach (['activate-release.sh', 'activate-incremental-release.sh'] as $file) {
$this->assertMatchesRegularExpression('/^10 5 \* \* \* .*run-finance-batch\.sh courier:sync-unshipped-waybills\b/m',
$this->assertMatchesRegularExpression('/^10 7 \* \* \* .*run-finance-batch\.sh courier:sync-unshipped-waybills\b/m',
file_get_contents(base_path('deploy/'.$file)));
}
}
@ -145,6 +145,29 @@ final class UnshippedWaybillsTest extends FeatureTestCase
$this->assertSame(['HISTORY1', 'NEW27'], $service->results()->orderBy('waybill_no')->pluck('waybill_no')->all());
}
public function test_shipping_record_supplies_replacement_evidence_without_operation_log(): void
{
$service=app(UnshippedWaybills::class);$db=$service->connection();
$db->table('jst_oms_shipping')->insert([
['source_id'=>71,'front_no'=>'@OLD71','express_no'=>'NEW71','trade_no'=>'T71','ship_time'=>'2026-11-28','express_name1'=>'测试快递'],
['source_id'=>72,'front_no'=>'OLD72','express_no'=>'NEW72','trade_no'=>'T72','ship_time'=>'2026-11-28','express_name1'=>'测试快递'],
['source_id'=>73,'front_no'=>null,'express_no'=>'OLD72','trade_no'=>'T73','ship_time'=>'2026-11-28','express_name1'=>'测试快递'],
]);
$this->assertTrue($service->sync('replacement'));
$this->assertSame(['OLD71'=>['换单未发出']],$service->unshippedSources(['OLD71','OLD72','NEW71']));
$this->assertStringContainsString('非换单操作时间',$service->results()->sole()->evidence_text);
}
public function test_staged_publish_preserves_history_and_does_not_expose_partial_rows(): void
{
$service=app(UnshippedWaybills::class);$db=$service->connection();
$service->results()->insert(['source'=>'warehouse','waybill_no'=>'HISTORY','evidence_no'=>'history:2026-11-26','evidence_time'=>'2026-11-26']);
foreach(['one','two'] as $generation)$db->table('courier_unshipped_stage')->insert(['source'=>'warehouse','row_key'=>hash('sha256',$generation),'generation'=>$generation,'waybill_no'=>strtoupper($generation),'evidence_no'=>$generation,'evidence_time'=>'2026-11-28']);
$this->assertSame(1,$service->results()->count());
$this->assertSame(1,$service->publishStage('warehouse','two',0));
$this->assertSame(['HISTORY','TWO'],$service->results()->orderBy('waybill_no')->pluck('waybill_no')->all());
}
private function mirrorRows(string $table, array $fields, array $rows): void
{
$connection = app(UnshippedWaybills::class)->connection();