137 lines
9.4 KiB
PHP
137 lines
9.4 KiB
PHP
<?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]));
|
|
}
|
|
}
|