182 lines
12 KiB
PHP
182 lines
12 KiB
PHP
<?php
|
|
|
|
namespace App\Support;
|
|
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Str;
|
|
use Modules\EcommerceFinance\Services\UpstreamReadOnlyQueryFactory;
|
|
use RuntimeException;
|
|
|
|
/** 只校准现有包裹的运单标识,不重算商品、重量或运费。 */
|
|
class ShippingTrackingRefresh
|
|
{
|
|
public const DATASET = 'derived.shipping-tracking-refresh';
|
|
private ?bool $hasDetailsMirror = null;
|
|
|
|
public function __construct(private readonly UpstreamReadOnlyQueryFactory $queries) {}
|
|
|
|
public function sync(array $ids = [], int $maxBatches = 4): array
|
|
{
|
|
$db = DB::connection('business_mirror');
|
|
$state = $db->table('business_mirror_table_states')->where('dataset_key', self::DATASET)->first();
|
|
$cursor = $state ? json_decode($state->cursor ?? 'null', true) : null;
|
|
$targeted = $ids !== [];
|
|
$resume = !$targeted && is_array($cursor) && in_array($state->status, ['running', 'failed'], true);
|
|
$watermark = $state ? json_decode($state->high_watermark ?? 'null', true) : null;
|
|
$from = $resume ? $cursor['from'] : (isset($watermark['until'])
|
|
? \Illuminate\Support\Carbon::parse($watermark['until'])->subHours(48)->format('Y-m-d H:i:s')
|
|
: now()->subHours(48)->format('Y-m-d H:i:s'));
|
|
$until = $resume ? $cursor['until'] : now()->addSecond()->format('Y-m-d H:i:s');
|
|
$last = $resume ? (int) $cursor['last_id'] : 0;
|
|
$generation = $resume ? $state->generation : (string) Str::uuid();
|
|
$scanned = $resume ? (int)($cursor['scanned']??0) : 0;
|
|
$changed = $resume ? (int)($cursor['changed']??0) : 0;
|
|
$base = ['source_key'=>'operations_replica','source_object'=>'rpt.jst_order_express_details',
|
|
'target_table'=>'jst_oms_shipping','run_mode'=>'incremental','generation'=>$generation,
|
|
'status'=>'running','last_attempted_at'=>now(),'last_error_code'=>null,'updated_at'=>now()];
|
|
if (!$targeted) $db->table('business_mirror_table_states')->updateOrInsert(['dataset_key'=>self::DATASET], $base + [
|
|
'cursor'=>json_encode(['from'=>$from,'until'=>$until,'last_id'=>$last,'scanned'=>$scanned,'changed'=>$changed]),
|
|
'created_at'=>$state->created_at??now()]);
|
|
try {
|
|
$names = $this->repairMissingCourierNames($generation);
|
|
for ($batch=0; $batch<max(1,$maxBatches); $batch++) {
|
|
$keys = $targeted ? array_values(array_unique(array_map('intval',$ids))) : $this->keys($last,$from,$until);
|
|
$scanned += count($keys);
|
|
$existing = $keys === [] ? [] : $db->table('jst_oms_shipping')->whereIn('source_id',$keys)->distinct()->pluck('source_id')->all();
|
|
foreach (array_chunk($existing,200) as $part) {
|
|
$current = $db->table('jst_oms_shipping')->whereIn('source_id',$part)
|
|
->distinct()->get(['source_id','express_no','express_name1'])->groupBy('source_id');
|
|
foreach ($this->details($part) as $row) {
|
|
$new = UnshippedWaybills::normalize($row['logistic_id']??null);
|
|
$name = trim((string)($row['logistic_company_name']??''));
|
|
$same = ($current[$row['id']]??collect())->every(fn($r)=>UnshippedWaybills::normalize($r->express_no)===$new
|
|
&& ($name==='' || (string)$r->express_name1===$name));
|
|
if ($same) continue;
|
|
$changed += $this->apply($row, $generation);
|
|
}
|
|
}
|
|
if ($targeted || count($keys)<5000) {
|
|
if (!$targeted) $db->table('business_mirror_table_states')->where('dataset_key',self::DATASET)->update([
|
|
'status'=>'succeeded','cursor'=>null,'high_watermark'=>json_encode(['until'=>$until]),'last_succeeded_at'=>now(),'initial_completed_at'=>$state->initial_completed_at??now(),'last_upserted_rows'=>$changed,'updated_at'=>now()]);
|
|
return ['status'=>'succeeded','scanned'=>$scanned,'changed'=>$changed,'names'=>$names];
|
|
}
|
|
$next = (int) end($keys);
|
|
if ($next <= $last) throw new RuntimeException('tracking_cursor_not_advanced');
|
|
$last=$next;
|
|
$db->table('business_mirror_table_states')->where('dataset_key',self::DATASET)->update([
|
|
'cursor'=>json_encode(['from'=>$from,'until'=>$until,'last_id'=>$last,'scanned'=>$scanned,'changed'=>$changed]),'last_upserted_rows'=>$changed,'updated_at'=>now()]);
|
|
}
|
|
return ['status'=>'running','scanned'=>$scanned,'changed'=>$changed,'names'=>$names];
|
|
} catch (\Throwable $e) {
|
|
if (!$targeted) $db->table('business_mirror_table_states')->where('dataset_key',self::DATASET)->update(['status'=>'failed','last_error_code'=>$e::class,'updated_at'=>now()]);
|
|
throw $e;
|
|
}
|
|
}
|
|
|
|
protected function keys(int $last,string $from,string $until): array
|
|
{
|
|
// 先取窄键,再按明确主键读详情,避免宽行加日期过滤扫描超时。
|
|
return array_column($this->queries->forSourceWithTimeout('operations_replica',30)->select(
|
|
'SELECT TOP (5000) id FROM rpt.jst_order_express_details WHERE id > CAST(? AS int) AND updatedAt >= CAST(? AS datetime) AND updatedAt < CAST(? AS datetime) ORDER BY id',
|
|
[$last,$from,$until]),'id');
|
|
}
|
|
|
|
protected function details(array $ids): array
|
|
{
|
|
return $this->queries->forSourceWithTimeout('operations_replica',30)->select(
|
|
'SELECT id,updatedAt,inner_order_id,so_id,logistic_id,logistic_company_name FROM rpt.jst_order_express_details WHERE id IN ('
|
|
.implode(',',array_fill(0,count($ids),'CAST(? AS int)')).') ORDER BY id',$ids);
|
|
}
|
|
|
|
public function apply(array $source, string $generation): int
|
|
{
|
|
$db=DB::connection('business_mirror');$new=UnshippedWaybills::normalize($source['logistic_id']??null);
|
|
if ($new==='' || strcasecmp($new,'OuterWMS')===0) return 0;
|
|
return $db->transaction(function() use($db,$source,$new,$generation): int {
|
|
$rows=$db->table('jst_oms_shipping')->where('source_id',(int)$source['id'])->lockForUpdate()->get();
|
|
if($rows->isEmpty()) return 0;
|
|
$old=UnshippedWaybills::normalize($rows->first()->express_no);
|
|
$courier=trim((string)($source['logistic_company_name']??''));
|
|
$mirror = $this->hasDetailsMirror()
|
|
? $db->table('js_jst_order_express_details')->where('id',(int)$source['id'])->first() : null;
|
|
$sameMirror = !$mirror || (UnshippedWaybills::normalize($mirror->logistic_id)===$new
|
|
&& ($courier==='' || (string)$mirror->logistic_company_name===$courier));
|
|
if($sameMirror && $rows->every(fn($r)=>UnshippedWaybills::normalize($r->express_no)===$new
|
|
&& ($courier==='' || (string)$r->express_name1===$courier))) return 0;
|
|
if(!$rows->every(fn($r)=>(string)$r->trade_no===trim((string)($source['so_id']??'')))) throw new RuntimeException('tracking_order_mismatch');
|
|
$this->backup($generation, (string)$source['id'], ['before'=>$rows->all(),'mirror_before'=>$mirror,'source'=>$source]);
|
|
$set=['express_no'=>$new];if($courier!=='')$set['express_name1']=$courier;
|
|
if($old!=='' && $old!==$new && strcasecmp($old,'OuterWMS')!==0){
|
|
$set['front_no']=$old;
|
|
self::recordChange((int)$source['id'],$old,(string)$rows->first()->express_name1,$new,$courier,
|
|
(string)($source['updatedAt']??now()),(string)$rows->first()->trade_no);
|
|
}
|
|
$db->table('jst_oms_shipping')->where('source_id',(int)$source['id'])->update($set);
|
|
if ($mirror !== null) {
|
|
$db->table('js_jst_order_express_details')->where('id',(int)$source['id'])->update([
|
|
'logistic_id'=>$new, 'logistic_company_name'=>$courier?:$mirror->logistic_company_name,
|
|
]);
|
|
}
|
|
return 1;
|
|
});
|
|
}
|
|
|
|
private function hasDetailsMirror(): bool
|
|
{
|
|
return $this->hasDetailsMirror ??= DB::connection('business_mirror')->getSchemaBuilder()->hasTable('js_jst_order_express_details');
|
|
}
|
|
|
|
/** 只补已有换单记录中有同源、同旧单号证据的空名称;每轮有界读取。 */
|
|
private function repairMissingCourierNames(string $generation): int
|
|
{
|
|
$db = DB::connection('business_mirror');
|
|
if (!$this->hasDetailsMirror()) return 0;
|
|
$rows = $db->table('courier_unshipped_waybills')->where('source','replacement')
|
|
->whereNull('courier_name')->where('evidence_no','like','shipping:%')->orderBy('id')->limit(500)->get();
|
|
$ids = $rows->map(fn($r)=>(int)substr($r->evidence_no,9))->all();
|
|
$details = $db->table('js_jst_order_express_details')->whereIn('id',$ids)
|
|
->get(['id','logistic_id','logistic_company_name'])->keyBy('id');
|
|
$changed = 0;
|
|
foreach ($rows as $row) {
|
|
$source = $details[(int)substr($row->evidence_no,9)] ?? null;
|
|
$name = trim((string)($source->logistic_company_name ?? ''));
|
|
if (!$source || $name==='' || UnshippedWaybills::normalize($source->logistic_id)!==$row->waybill_no) continue;
|
|
$this->backup($generation, 'name-'.$row->id, ['before'=>$row,'source'=>$source]);
|
|
$changed += $db->table('courier_unshipped_waybills')->where('id',$row->id)->whereNull('courier_name')->update(['courier_name'=>$name]);
|
|
}
|
|
return $changed;
|
|
}
|
|
|
|
private function backup(string $generation, string $key, array $data): void
|
|
{
|
|
$dir=storage_path('app/private/maintenance/tracking-refresh/'.$generation);
|
|
if(!is_dir($dir) && !mkdir($dir,0700,true) && !is_dir($dir)) throw new RuntimeException('tracking_backup_failed');
|
|
$payload=json_encode($data,JSON_UNESCAPED_UNICODE|JSON_THROW_ON_ERROR);
|
|
$path=$dir.'/'.$key.'-'.bin2hex(random_bytes(4)).'.json';
|
|
if(file_put_contents($path,$payload,LOCK_EX)!==strlen($payload)) throw new RuntimeException('tracking_backup_failed');
|
|
chmod($path,0600);
|
|
}
|
|
|
|
public static function recordChange(int $sourceId,string $old,string $oldCourier,string $new,string $newCourier,string $time,string $trade): void
|
|
{
|
|
$old=UnshippedWaybills::normalize($old);$new=UnshippedWaybills::normalize($new);
|
|
if($old===''||$new===''||$old===$new||strcasecmp($old,'OuterWMS')===0||strcasecmp($new,'OuterWMS')===0)return;
|
|
$db=DB::connection('business_mirror');$order='shipping:'.$sourceId;
|
|
$log=['old_waybill'=>$old,'new_waybill'=>$new,'old_courier'=>$oldCourier,'new_courier'=>$newCourier,
|
|
'operator'=>'系统同步','remark'=>$oldCourier.':'.$old.'->'.$newCourier.':'.$new];
|
|
$db->table('courier_unshipped_order_logs')->updateOrInsert(['order_no'=>$order,'operated_at'=>$time,'old_waybill'=>$old],$log);
|
|
if (!$db->table('jst_oms_shipping')->where('source_id','<>',$sourceId)->whereIn('express_no',[$old,'@'.$old])->exists()) {
|
|
$db->table('courier_unshipped_waybills')->updateOrInsert(['source'=>'replacement','evidence_no'=>$order,'waybill_no'=>$old],
|
|
['courier_name'=>$oldCourier?:null,'new_waybill_no'=>$new,'new_courier_name'=>$newCourier?:null,'trade_no'=>$trade,
|
|
'evidence_time'=>$time,'evidence_text'=>'按同一包裹源键核实换单前后信息','operator'=>'系统同步']);
|
|
}
|
|
$db->table('courier_unshipped_waybills')->where('source','replacement')->where('evidence_no',$order)
|
|
->update(['new_waybill_no'=>$new,'new_courier_name'=>$newCourier?:null]);
|
|
// A→B→A 时,最终正在使用的号码不再作为未发出旧号。
|
|
$db->table('courier_unshipped_waybills')->where('source','replacement')->where('evidence_no',$order)->where('waybill_no',$new)->delete();
|
|
$db->table('courier_unshipped_sync')->where('source','replacement')->update([
|
|
'row_count'=>$db->table('courier_unshipped_waybills')->where('source','replacement')->count(),
|
|
]);
|
|
}
|
|
}
|