119 lines
11 KiB
PHP
119 lines
11 KiB
PHP
<?php
|
||
namespace App\Services\OrderReporting;
|
||
use App\Jobs\DeliverOrderReport;
|
||
use App\Models\{Order,OrderReportEvent};
|
||
use Carbon\CarbonImmutable;
|
||
use Illuminate\Support\Facades\{DB,Http,Log};
|
||
use RuntimeException;
|
||
|
||
class Reporter
|
||
{
|
||
private const ACTIVE=['pending','queued','sending'];
|
||
private const TERMINAL=['sent','failed','uncertain','cancelled'];
|
||
public function enabled():bool { return config('order_report.enabled',false)&&config('app.env')==='production'; }
|
||
public function identity():string {
|
||
$driver=(string)config('database.default');
|
||
return substr(hash('sha256',implode('|',[(string)config('app.env'),(string)config('order_report.project'),(string)config('app.url'),$driver,(string)config('database.connections.'.$driver.'.database')])),0,24);
|
||
}
|
||
public function initialize(?int $firstPaidAt=null):OrderReportEvent {
|
||
$configured=config('order_report.start_at');
|
||
if($configured!==null&&(!ctype_digit((string)$configured)||(int)$configured<0))throw new RuntimeException('order_report_start_invalid');
|
||
$control=OrderReportEvent::firstOrCreate(['business_key'=>'xb.order.control.'.$this->identity()],['identity'=>$this->identity(),'kind'=>'control','status'=>'control','payload'=>['started_at'=>$configured===null?($firstPaidAt??now()->timestamp):(int)$configured]]);
|
||
if($control->identity!==$this->identity()||!is_int($control->payload['started_at']??null))throw new RuntimeException('order_report_control_invalid');
|
||
return $control;
|
||
}
|
||
public function capture(Order $order):?OrderReportEvent {
|
||
if(!$this->enabled()||!config('order_report.payment_enabled',true))return null;
|
||
if(!in_array((int)$order->status,[Order::STATUS_PROCESSING,Order::STATUS_COMPLETED,Order::STATUS_DISCOUNTED],true)||(int)$order->paid_at<=0)return null;
|
||
$control=$this->initialize((int)$order->paid_at);
|
||
if((int)$order->paid_at<$control->payload['started_at'])return null;
|
||
$cash=max(0,(int)$order->total_amount);$fee=$cash>0?max(0,(int)$order->handling_amount):0;$balance=max(0,(int)$order->balance_amount);
|
||
$facts=['order_id'=>(int)$order->id,'paid_at'=>(int)$order->paid_at,'gateway_cents'=>$cash+$fee,'fee_cents'=>$fee,'balance_cents'=>$balance,'total_cents'=>$cash+$fee+$balance];
|
||
$text=$this->title('订单付款成功')."\n订单:#".$order->id."\n付款时间:".CarbonImmutable::createFromTimestamp($order->paid_at,'Asia/Shanghai')->format('Y-m-d H:i:s').'(北京时间)';
|
||
$text.="\n付款金额:¥".$this->money($facts['total_cents'])."\n网关付款:¥".$this->money($facts['gateway_cents']).'(其中手续费¥'.$this->money($fee).')';
|
||
$text.="\n余额支付:¥".$this->money($balance);
|
||
if($facts['total_cents']===0)$text.="\n零元完成,不计入付款笔数或金额。";
|
||
return OrderReportEvent::firstOrCreate(['business_key'=>'xb.order.paid.'.$this->identity().'.'.$order->id],['identity'=>$this->identity(),'kind'=>'payment','order_id'=>$order->id,'bot'=>'log','payload'=>['bot'=>'log','target'=>'base','text'=>$text,'facts'=>$facts]]);
|
||
}
|
||
public function queue(int $id):void {
|
||
if(!$this->enabled())return;
|
||
$now=now()->timestamp;
|
||
$claimed=OrderReportEvent::whereKey($id)->where('identity',$this->identity())->whereIn('status',self::ACTIVE)->where('next_attempt_at','<=',$now)->where('lease_until','<=',$now)->where('queued_until','<=',$now)->update(['queued_until'=>$now+120]);
|
||
if(!$claimed)return;
|
||
try { DeliverOrderReport::dispatch($id)->onConnection('redis')->onQueue('send_telegram'); }
|
||
catch(\Throwable $e){OrderReportEvent::whereKey($id)->update(['queued_until'=>0,'error_code'=>'queue_unavailable']);Log::warning('order_report_queue_deferred',['event_id'=>$id,'error_type'=>get_class($e)]);}
|
||
}
|
||
public function reconcile():int {
|
||
if(!$this->enabled())return 0;
|
||
$control=$this->initialize();$count=0;
|
||
if(config('order_report.payment_enabled',true)){
|
||
$orders=Order::whereIn('status',[1,3,4])->where('paid_at','>=',$control->payload['started_at'])->where('paid_at','>',0)
|
||
->whereNotExists(function($q){$q->selectRaw('1')->from('v2_order_report_events as e')->whereColumn('e.order_id','v2_order.id')->where('e.kind','payment')->where('e.identity',$this->identity());})
|
||
->orderBy('paid_at')->orderBy('id')->limit(100)->get();
|
||
foreach($orders as $order){if($this->capture($order))$count++;}
|
||
}
|
||
return $count;
|
||
}
|
||
public function daily(?CarbonImmutable $now=null):?OrderReportEvent {
|
||
if(!$this->enabled()||!config('order_report.daily_enabled',true))return null;
|
||
$now=($now??CarbonImmutable::now())->setTimezone('Asia/Shanghai');$end=$now->startOfDay()->setTime(8,0);
|
||
if($now->lessThan($end))return null;
|
||
$key='xb.order.daily.'.$this->identity().'.'.$end->toDateString();
|
||
if($existing=OrderReportEvent::where('business_key',$key)->first())return $existing;
|
||
$start=$end->subDay();
|
||
$data=Order::whereIn('status',[1,3,4])->where('paid_at','>=',$start->timestamp)->where('paid_at','<',$end->timestamp)
|
||
->selectRaw('COUNT(*) as completed, SUM(CASE WHEN total_amount > 0 OR balance_amount > 0 THEN 1 ELSE 0 END) as paid_count, SUM(CASE WHEN total_amount > 0 THEN total_amount ELSE 0 END) as cash, SUM(CASE WHEN total_amount > 0 AND handling_amount > 0 THEN handling_amount ELSE 0 END) as fees, SUM(CASE WHEN balance_amount > 0 THEN balance_amount ELSE 0 END) as balance')->first();
|
||
$facts=['date'=>$end->toDateString(),'start_at'=>$start->timestamp,'end_at'=>$end->timestamp,'paid_count'=>(int)$data->paid_count,'zero_count'=>(int)$data->completed-(int)$data->paid_count,'gateway_cents'=>(int)$data->cash+(int)$data->fees,'fee_cents'=>(int)$data->fees,'balance_cents'=>(int)$data->balance];
|
||
$facts['total_cents']=$facts['gateway_cents']+$facts['balance_cents'];
|
||
$text=$this->title('付款订单日报')."\n统计区间:".$start->format('Y-m-d H:i').'–'.$end->format('Y-m-d H:i').'(北京时间)';
|
||
$text.="\n付款订单:".$facts['paid_count'].' 笔' ."\n总付款金额:¥".$this->money($facts['total_cents']);
|
||
$text.="\n网关付款:¥".$this->money($facts['gateway_cents']).'(其中手续费¥'.$this->money($facts['fee_cents']).')' ."\n余额支付:¥".$this->money($facts['balance_cents']);
|
||
$text.="\n零元完成:".$facts['zero_count'].' 笔(不计入付款笔数或金额)';
|
||
return OrderReportEvent::firstOrCreate(['business_key'=>$key],['identity'=>$this->identity(),'kind'=>'daily','report_date'=>$end->toDateString(),'bot'=>'info','payload'=>['bot'=>'info','target'=>'base','text'=>$text,'facts'=>$facts]]);
|
||
}
|
||
public function queueDue():int {
|
||
if(!$this->enabled())return 0;
|
||
$kinds=[];if(config('order_report.payment_enabled',true))$kinds[]='payment';if(config('order_report.daily_enabled',true))$kinds[]='daily';
|
||
$events=OrderReportEvent::where('identity',$this->identity())->whereIn('kind',$kinds)->whereIn('status',self::ACTIVE)->where('next_attempt_at','<=',now()->timestamp)->where('lease_until','<=',now()->timestamp)->where('queued_until','<=',now()->timestamp)->orderBy('id')->limit(20)->pluck('id');
|
||
foreach($events as $id)$this->queue((int)$id);
|
||
return $events->count();
|
||
}
|
||
public function deliver(int $id):void {
|
||
if(!$this->enabled())return;
|
||
$event=OrderReportEvent::whereKey($id)->where('identity',$this->identity())->first();
|
||
if(!$event||!in_array($event->status,self::ACTIVE,true))return;
|
||
if(($event->kind==='payment'&&!config('order_report.payment_enabled',true))||($event->kind==='daily'&&!config('order_report.daily_enabled',true)))return;
|
||
$bot=$event->kind==='payment'?'log':($event->kind==='daily'?'info':null);$p=$event->payload;
|
||
if(!$bot||$event->bot!==$bot||($p['bot']??null)!==$bot||($p['target']??null)!=='base'||!is_string($p['text']??null)||mb_strlen($p['text'])>4096||!preg_match('/\A[A-Za-z0-9._:-]{1,128}\z/D',$event->business_key)){$event->update(['status'=>'failed','queued_until'=>0,'error_code'=>'event_invalid']);return;}
|
||
$base=rtrim((string)config('order_report.telehub_url'),'/');$key=(string)config('order_report.telehub_key');
|
||
if(!$key||parse_url($base,PHP_URL_SCHEME)!=='https'||!parse_url($base,PHP_URL_HOST)||parse_url($base,PHP_URL_USER)||parse_url($base,PHP_URL_PASS)||parse_url($base,PHP_URL_QUERY)||parse_url($base,PHP_URL_FRAGMENT)){
|
||
$event->update(['error_code'=>'telehub_configuration_required','queued_until'=>0,'next_attempt_at'=>now()->timestamp+300]);return;
|
||
}
|
||
if($event->receipt_id&&!$this->uuid($event->receipt_id)){$event->update(['status'=>'failed','queued_until'=>0,'error_code'=>'receipt_invalid']);return;}
|
||
$now=now()->timestamp;
|
||
$lease=OrderReportEvent::whereKey($id)->whereIn('status',self::ACTIVE)->where('lease_until','<=',$now)->where('next_attempt_at','<=',$now)->update(['lease_until'=>$now+60,'queued_until'=>0,'next_attempt_at'=>$now+max(60,(int)config('order_report.retry_seconds',300)),'attempts'=>DB::raw('attempts + 1')]);
|
||
if(!$lease)return;
|
||
try {
|
||
$event->refresh();$client=Http::withoutRedirecting()->connectTimeout(5)->timeout(15)->withToken($key);
|
||
try {$response=$event->receipt_id?$client->get($base.'/api/v1/messages/'.$event->receipt_id):$client->withHeaders(['Idempotency-Key'=>$event->business_key])->post($base.'/api/v1/messages',['bot'=>$bot,'target'=>'base','text'=>$p['text']]);}
|
||
catch(\Throwable $e){$event->update(['error_code'=>'telehub_transport_unknown']);return;}
|
||
if(!in_array($response->status(),[200,202],true)){
|
||
$updates=['error_code'=>'telehub_http_'.$response->status()];
|
||
if($response->status()===429)$updates['next_attempt_at']=$now+max(60,min(86400,(int)$response->header('Retry-After',300)));
|
||
elseif(in_array($response->status(),[400,401,403,404,409,422],true))$updates['status']='failed';
|
||
$event->update($updates);return;
|
||
}
|
||
$data=$response->json('data');$receipt=is_array($data)?($data['id']??null):null;$status=is_array($data)?($data['status']??null):null;
|
||
if(!$this->uuid($receipt)||!in_array($status,['queued','sending',...self::TERMINAL],true)||($event->receipt_id&&$receipt!==$event->receipt_id)){$event->update(['error_code'=>'telehub_response_invalid']);return;}
|
||
$event->update(['receipt_id'=>$receipt,'status'=>$status,'error_code'=>in_array($status,['failed','uncertain'],true)?'telehub_delivery_'.$status:null]);
|
||
} finally { OrderReportEvent::whereKey($id)->update(['lease_until'=>0]); }
|
||
}
|
||
private function title(string $subject):string {
|
||
$project=trim(preg_replace('/[\x00-\x1f\x7f]+/u',' ',(string)config('order_report.project')));
|
||
if($project===''||mb_strlen($project)>100)throw new RuntimeException('order_report_project_invalid');
|
||
return '【'.$project.'/'.config('app.env').' - '.$subject.'】';
|
||
}
|
||
private function money(int $cents):string { return intdiv($cents,100).'.'.str_pad((string)($cents%100),2,'0',STR_PAD_LEFT); }
|
||
private function uuid(mixed $id):bool { return is_string($id)&&preg_match('/\A[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\z/iD',$id)===1; }
|
||
}
|