From 91b5e1251f82f529fe26d2f325a45bc525e46a47 Mon Sep 17 00:00:00 2001 From: hellcat Date: Sun, 1 Nov 2026 13:51:09 +0800 Subject: [PATCH] feat(orders): add asynchronous payment logs and 08:00 daily reports --- app/Console/Commands/ReportOrderPayments.php | 14 +++ app/Console/Kernel.php | 5 + app/Jobs/DeliverOrderReport.php | 15 +++ app/Models/OrderReportEvent.php | 9 ++ app/Services/OrderReporting/Reporter.php | 118 ++++++++++++++++++ app/Services/OrderService.php | 26 +++- config/order_report.php | 11 ++ ...1_01_090000_create_order_report_events.php | 18 +++ docs/maintenance/ORDER_REPORTS.md | 39 ++++++ docs/maintenance/README.md | 1 + .../OrderReporting/OrderReportingTest.php | 107 ++++++++++++++++ 11 files changed, 360 insertions(+), 3 deletions(-) create mode 100644 app/Console/Commands/ReportOrderPayments.php create mode 100644 app/Jobs/DeliverOrderReport.php create mode 100644 app/Models/OrderReportEvent.php create mode 100644 app/Services/OrderReporting/Reporter.php create mode 100644 config/order_report.php create mode 100644 database/migrations/2026_11_01_090000_create_order_report_events.php create mode 100644 docs/maintenance/ORDER_REPORTS.md create mode 100644 tests/Feature/OrderReporting/OrderReportingTest.php diff --git a/app/Console/Commands/ReportOrderPayments.php b/app/Console/Commands/ReportOrderPayments.php new file mode 100644 index 00000000..ad62a0c0 --- /dev/null +++ b/app/Console/Commands/ReportOrderPayments.php @@ -0,0 +1,14 @@ +enabled())return self::SUCCESS; + try {$recovered=$reports->reconcile();$daily=$reports->daily();$queued=$reports->queueDue();$this->line(json_encode(['recovered'=>$recovered,'daily_event_id'=>$daily?->id,'queued'=>$queued]));return self::SUCCESS;} + catch(\Throwable $e){$this->error('order_report_failed_closed: '.get_class($e));return self::FAILURE;} + } +} diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index 7782d1e0..063343a8 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -33,6 +33,11 @@ class Kernel extends ConsoleKernel $schedule->command('report:registrations')->timezone('Asia/Shanghai')->dailyAt('08:00')->onOneServer()->withoutOverlapping(10)->createMutexNameUsing($registrationMutex.'-daily')->when(fn () => config('registration_report.enabled', false)); $schedule->command('report:registrations')->everyFiveMinutes()->onOneServer()->withoutOverlapping(10)->createMutexNameUsing($registrationMutex.'-retry')->when(fn () => config('registration_report.enabled', false)); + // Each instance keeps its own durable payment-event outbox and notification worker. + $orderMutex = 'xb-order-reports-'.hash('sha256', (string)config('order_report.project').'|'.(string)config('app.url')); + $schedule->command('orders:report-payments')->everyMinute()->onOneServer()->withoutOverlapping(5)->createMutexNameUsing($orderMutex.'-retry')->when(fn () => config('order_report.enabled', false)); + $schedule->command('orders:report-payments')->timezone('Asia/Shanghai')->dailyAt('08:00')->onOneServer()->withoutOverlapping(5)->createMutexNameUsing($orderMutex.'-daily')->when(fn () => config('order_report.enabled', false)); + $schedule->command('payment:health-check')->timezone('Asia/Shanghai')->cron('0 */6 * * *')->withoutOverlapping(30); Cache::put(CacheKey::get('SCHEDULE_LAST_CHECK_AT', null), time()); // v2board diff --git a/app/Jobs/DeliverOrderReport.php b/app/Jobs/DeliverOrderReport.php new file mode 100644 index 00000000..d3d15bfb --- /dev/null +++ b/app/Jobs/DeliverOrderReport.php @@ -0,0 +1,15 @@ +onConnection('redis')->onQueue('send_telegram'); } + public function handle(Reporter $reports): void { $reports->deliver($this->eventId); } +} diff --git a/app/Models/OrderReportEvent.php b/app/Models/OrderReportEvent.php new file mode 100644 index 00000000..bb0e8454 --- /dev/null +++ b/app/Models/OrderReportEvent.php @@ -0,0 +1,9 @@ +'array','next_attempt_at'=>'integer','lease_until'=>'integer','queued_until'=>'integer','attempts'=>'integer']; +} diff --git a/app/Services/OrderReporting/Reporter.php b/app/Services/OrderReporting/Reporter.php new file mode 100644 index 00000000..ca22b17d --- /dev/null +++ b/app/Services/OrderReporting/Reporter.php @@ -0,0 +1,118 @@ +'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; } +} diff --git a/app/Services/OrderService.php b/app/Services/OrderService.php index a7fbd556..6f587fd9 100644 --- a/app/Services/OrderService.php +++ b/app/Services/OrderService.php @@ -326,13 +326,13 @@ class OrderService public function paid(string $callbackNo) { try { - [$order, $shouldDispatch] = DB::transaction(function () use ($callbackNo) { + [$order, $shouldDispatch, $reportId] = DB::transaction(function () use ($callbackNo) { $order = $this->lockCurrentOrder(); if (!$order) { throw new \RuntimeException('Order not found.'); } if ((int) $order->status !== Order::STATUS_PENDING) { - return [$order, false]; + return [$order, false, null]; } $order->status = Order::STATUS_PROCESSING; @@ -342,12 +342,32 @@ class OrderService throw new \RuntimeException('Failed to save order status.'); } - return [$order, true]; + $reportId = null; + try { + // A local outbox savepoint must never make a confirmed payment fail. + $reportId = DB::transaction(fn () => app(\App\Services\OrderReporting\Reporter::class)->capture($order)?->id); + } catch (\Throwable $e) { + Log::warning('order_report_capture_deferred', ['order_id' => $order->id, 'error_type' => get_class($e)]); + } + return [$order, true, $reportId]; }); $this->order = $order; if ($shouldDispatch) { + if ($reportId) { + try { + DB::afterCommit(function () use ($reportId) { + $enqueue = function () use ($reportId) { + try { app(\App\Services\OrderReporting\Reporter::class)->queue($reportId); } + catch (\Throwable $e) { Log::warning('order_report_dispatch_deferred', ['event_id' => $reportId, 'error_type' => get_class($e)]); } + }; + // HTTP: push only after the response is sent. CLI: no customer response is waiting. + if (app()->runningInConsole()) $enqueue(); + else app()->terminating($enqueue); + }); + } catch (\Throwable $e) { Log::warning('order_report_dispatch_deferred', ['event_id' => $reportId, 'error_type' => get_class($e)]); } + } OrderHandleJob::dispatchSync($order->trade_no); } } catch (\Exception $e) { diff --git a/config/order_report.php b/config/order_report.php new file mode 100644 index 00000000..4ebb33ee --- /dev/null +++ b/config/order_report.php @@ -0,0 +1,11 @@ + env('ORDER_REPORT_ENABLED', true), + 'payment_enabled' => env('ORDER_REPORT_PAYMENT_ENABLED', true), + 'daily_enabled' => env('ORDER_REPORT_DAILY_ENABLED', true), + 'project' => env('ORDER_REPORT_PROJECT', env('XB_INSTANCE', env('SITE_PROFILE', env('APP_NAME', 'xb')))), + 'telehub_url' => env('ORDER_REPORT_TELEHUB_URL', 'https://telehub.gemcook.net'), + 'telehub_key' => env('ORDER_REPORT_TELEHUB_KEY', ''), + 'start_at' => env('ORDER_REPORT_START_AT'), + 'retry_seconds' => 300, +]; diff --git a/database/migrations/2026_11_01_090000_create_order_report_events.php b/database/migrations/2026_11_01_090000_create_order_report_events.php new file mode 100644 index 00000000..4b334b08 --- /dev/null +++ b/database/migrations/2026_11_01_090000_create_order_report_events.php @@ -0,0 +1,18 @@ +id();$t->string('business_key',128)->unique();$t->string('identity',24)->index();$t->string('kind',16); + $t->unsignedBigInteger('order_id')->nullable()->index();$t->date('report_date')->nullable();$t->string('bot',16)->nullable(); + $t->string('status',16)->default('pending');$t->json('payload');$t->string('receipt_id',36)->nullable(); + $t->unsignedBigInteger('next_attempt_at')->default(0);$t->unsignedBigInteger('lease_until')->default(0); + $t->unsignedBigInteger('queued_until')->default(0);$t->unsignedInteger('attempts')->default(0); + $t->string('error_code',100)->nullable();$t->timestamps(); + $t->index(['identity','status','next_attempt_at']); + }); + } + public function down(): void { Schema::dropIfExists('v2_order_report_events'); } +}; diff --git a/docs/maintenance/ORDER_REPORTS.md b/docs/maintenance/ORDER_REPORTS.md new file mode 100644 index 00000000..feb6bf79 --- /dev/null +++ b/docs/maintenance/ORDER_REPORTS.md @@ -0,0 +1,39 @@ +# 付款成功异步通知与付款日报 + +## 用户批准与金额口径 + +2026-11-01用户要求所有XB子项目默认开启:订单付款成功通知TeleHub log,每天08:00统计昨天08:00至今天08:00的付款笔数和总金额;暂停讨论后,用户明确接受不等待TeleHub的后台异步方案,并补充“8点的汇报走info,做”。该批准覆盖本批共用OrderService付款事件、通知记录表、后台任务/补偿、配置、测试与DPL/HN Git上线,不改变支付验签/收费/开通规则,不进行真实测试付款。 + +即时消息log/base,日报info/base;标题包含项目、生产环境和事项。每日窗口为Asia/Shanghai昨日08:00含至今日08:00不含,按paid_at(Unix秒)统计状态开通中/已完成/已折抵的成功订单。仅最新完整当期日报首次建立,不批量补历史,0笔也汇报。 + +金额全程以整数分计算:网关付款=total_amount+handling_amount(仅total_amount>0时计手续费),余额支付=balance_amount,总付款金额=两者之和。优惠/升级折抵不重新加回;余额分列,不能把它当新增现金收入。网关付款是订单应付口径,不冒充支付平台结算/银行到账金额。total_amount与balance_amount均为0的订单作为零元完成单独列示,不计付款笔数或金额;它的完成事件仍可发log并明确标记零元。 + +## 用户响应与异步链路 + +OrderService::paid仅在锁定订单后由待支付首次转开通中、记录paid_at时写本地通知记录。写入使用嵌套事务/保存点;失败只记录脱敏类别,不逆转已确认付款,补偿后续按paid_at查漏。支付事务回滚则通知记录也回滚,不发布通知。 + +在支付事务提交后,HTTP环境将入队动作注册到应用终止阶段(Laravel响应发送之后),再推送显式redis/send_telegram队列;控制台任务可直接入队。即使默认QUEUE_CONNECTION=sync也不在付款请求中调用TeleHub。Redis入队异常被隔离,通知记录保留,下一分钟恢复;PHP-FPM的终止阶段可能占用一小段worker时间,但客户响应已发出,不能承诺额外本地数据库写入绝对零耗时。 + +DeliverOrderReport由已有通知worker处理;不新增白色机/本机常驻任务。每分钟orders:report-payments负责查找启用起点之后的漏报订单、生成当天08点日报、恢复待发/待查回执,每批最多20个通知任务;另有显式08:00 Asia/Shanghai调度。补偿即使主机晚启动也固定同一窗口,不改成00点或滚动24小时。 + +## 持久化、默认值和授权 + +新增唯一表v2_order_report_events(独立于v2_order):control保存当前实例的启用起点;payment按实例+订单ID唯一;daily按实例+结束日期唯一。记录固定业务键、bot/target/text、金额与区间快照、UUID、下次重试、队列/发送租约和状态。无业务表结构/旧订单内容修改,表中不保存调用密钥、用户邮箱、完整支付链接或网关回调流水。 + +config/order_report.php默认enabled/payment_enabled/daily_enabled均true,所有子项目共用;只有production外发。旧缓存尚不认识该模块时按false守卫,避免抢先运行。可分别使用ORDER_REPORT_ENABLED、ORDER_REPORT_PAYMENT_ENABLED、ORDER_REPORT_DAILY_ENABLED关闭。私密ORDER_REPORT_PROJECT/TELEHUB_URL/TELEHUB_KEY配置分实例,专用ApiClient只授权log、info和base,不借用注册、邮件或支付健康凭据。 + +ORDER_REPORT_START_AT可显式固定首次启用Unix秒;未配置时control在首次运行持久化当前时刻,首次付款触发时取其paid_at。即时查漏不重放启用前旧订单;该起点不截断当期日报的完整24小时。身份绑定环境/项目/app.url/数据库,配置迁移不得盲目重绑定旧记录。 + +## 幂等与失败 + +先保存固定内容和Idempotency-Key,再由队列HTTP。重复支付回调不会再次创建记录/任务;队列短租约防重复排队,发送租约防并发,崩溃后租约过期可恢复。超时/5xx复用同一键与正文;取得UUID后仅GET原回执。429按Retry-After有界退避,其他常规重试至少5分钟。无重定向或旧master/Telegram直发回退。 + +queued/sending只是TeleHub受理/处理中;sent才表示Telegram确认。failed/uncertain/cancelled为终态,不自动重新发送;401/403/409/422等明确拒绝保留失败并停止自动重试。attempts为本地API次数,不能混作TeleHub实际投递次数。不可删除旧状态或变更固定正文来“补发”。 + +## 部署、验收与恢复 + +本批DPL/HN各准备独立调用方,仅log/info/base,密钥保留各服务器私密.env;先enabled=false。Git提交推送后服务器检出明确版本,分别执行本文件对应的单项增量迁移2026_11_01_090000_create_order_report_events.php,生成实例缓存,再开启原应用调度并验证。新表和迁移均为增量,保留所有原订单/用户/套餐/支付与其他汇报记录。 + +隔离测试覆盖不阻塞/提交后且HTTP响应后入队、回滚不发、队列/记录故障不逆转付款、重复回调、补偿漏单、旧订单不重放、完整时间边界、手续费/余额/零元、正文冻结、log/info路由、同键重试/回执、429/403/uncertain、租约、默认开启和实例隔离。本批156项隔离测试745断言通过,没有以生产订单造假或实际付款验收。额外尝试旧OrderServiceConcurrencyTest时因缺少v2_user基础建表fixture未通过,未计入通过数量;本批使用独立SQLite明确建表测试验证支付重复回调、外层回滚、记录/队列故障隔离与提交后派发。线上若暂无新真实付款,只报告即时通知模拟闭环与授权/worker检查通过,不声称真实订单log已验收;本期真实零笔日报可用于info通道完整验收。 + +优先单独停用ORDER_REPORT_ENABLED=false并以正确XB_INSTANCE/原用户刷新配置缓存,不停止其他邮件/注册/支付任务。代码回退前让本类已排队任务在关闭开关后退出,保留兼容job类直至确认没有在途本任务,不能清空共享send_telegram队列。保留新表、业务键、UUID和已发送记录,不做down/整库恢复,也不删除记录重发;新代码将来恢复后继续原回执。私密.env和其他并行变更按字段合并。实际SHA、备份与回执在本次上线后补录。 diff --git a/docs/maintenance/README.md b/docs/maintenance/README.md index 948e994a..d2a6250b 100644 --- a/docs/maintenance/README.md +++ b/docs/maintenance/README.md @@ -23,6 +23,7 @@ | 文件 | 用途 | | --- | --- | +| ORDER_REPORTS.md | 付款成功log异步通知、08点info日报、默认继承、幂等/租约与恢复 | | MAIL_REPORT_TELEHUB.md | DPL/HN邮件与Resend用量日报迁到TeleHub、历史保护、幂等回执及恢复 | | REGISTRATION_REPORT.md | 各实例默认每天08:00汇报昨日08点至今日08点注册量,TeleHub info/base、幂等回执及回退 | | PAYMENT_HEALTH.md | 共用支付每6小时检测、自动开关、人工停用/旧回调保护、独立TeleHub告警与生产验收 | diff --git a/tests/Feature/OrderReporting/OrderReportingTest.php b/tests/Feature/OrderReporting/OrderReportingTest.php new file mode 100644 index 00000000..16bae7bb --- /dev/null +++ b/tests/Feature/OrderReporting/OrderReportingTest.php @@ -0,0 +1,107 @@ +'sqlite','database.connections.sqlite.database'=>':memory:','cache.default'=>'array','cache.stores.redis'=>['driver'=>'array'],'app.env'=>'production','app.url'=>'https://dpl.example.test','queue.default'=>'sync','order_report.enabled'=>true,'order_report.payment_enabled'=>true,'order_report.daily_enabled'=>true,'order_report.project'=>'DPL','order_report.telehub_url'=>'https://telehub.example.test','order_report.telehub_key'=>'secret-order-key','order_report.start_at'=>CarbonImmutable::parse('2026-11-01 13:00','Asia/Shanghai')->timestamp,'order_report.retry_seconds'=>300]); + DB::purge('sqlite');Cache::forgetDriver(['redis','array']); + Schema::create('v2_order',function(Blueprint $t){$t->id();$t->string('trade_no');$t->integer('user_id')->nullable();$t->integer('plan_id')->nullable();$t->integer('payment_id')->nullable();$t->string('period')->nullable();$t->integer('type')->nullable();$t->integer('total_amount')->default(0);$t->integer('balance_amount')->nullable();$t->integer('handling_amount')->nullable();$t->integer('status')->default(0);$t->integer('paid_at')->nullable();$t->string('callback_no')->nullable();$t->integer('created_at')->nullable();$t->integer('updated_at')->nullable();}); + Schema::create('v2_plugins',fn(Blueprint $t)=>[$t->id(),$t->boolean('is_enabled')->default(false)]);Schema::create('v2_settings',fn(Blueprint $t)=>[$t->id(),$t->string('name'),$t->text('value')->nullable(),$t->timestamps()]);$this->app->forgetInstance(\App\Support\Setting::class); + $this->migrate();$this->travelTo(\Carbon\Carbon::parse('2026-11-01 14:00','Asia/Shanghai'));Bus::fake([DeliverOrderReport::class,OrderHandleJob::class]);Http::preventStrayRequests(); + } + private function migrate():void {(require base_path('database/migrations/2026_11_01_090000_create_order_report_events.php'))->up();} + private function order(array $attrs=[]):Order {return Order::create($attrs+['trade_no'=>'private-order-'.bin2hex(random_bytes(4)),'total_amount'=>1000,'balance_amount'=>200,'handling_amount'=>50,'status'=>1,'paid_at'=>now()->timestamp]);} + private function event():OrderReportEvent {return app(Reporter::class)->capture($this->order());} + private function response(string $status='queued',int $code=202){return Http::response(['data'=>['id'=>self::UUID,'status'=>$status]],$code);} + + public function test_payment_callback_only_records_and_queues_async_once_without_http():void { + $o=$this->order(['status'=>0,'paid_at'=>null]);$s=new OrderService($o);$this->assertTrue($s->paid('private-callback'));$this->assertTrue($s->paid('private-callback'));$this->assertSame(1,OrderReportEvent::where('kind','payment')->count());$e=OrderReportEvent::where('kind','payment')->first();$this->assertSame('log',$e->bot);Bus::assertDispatched(DeliverOrderReport::class,1);Bus::assertDispatched(DeliverOrderReport::class,fn($job)=>$job->connection==='redis'&&$job->queue==='send_telegram');Bus::assertDispatchedSync(OrderHandleJob::class,1);Http::assertNothingSent(); + } + public function test_http_payment_defers_even_redis_enqueue_until_application_termination():void { + $property=new \ReflectionProperty($this->app,'isRunningInConsole');$property->setAccessible(true);$previous=$property->getValue($this->app);$property->setValue($this->app,false); + try {$o=$this->order(['status'=>0,'paid_at'=>null]);$this->assertTrue((new OrderService($o))->paid('cb'));Bus::assertNotDispatched(DeliverOrderReport::class);$this->assertSame(1,OrderReportEvent::where('kind','payment')->count());$this->app->terminate();Bus::assertDispatched(DeliverOrderReport::class,1);Http::assertNothingSent();} + finally {$property->setValue($this->app,$previous);} + } + public function test_rolled_back_outer_transaction_does_not_queue_or_keep_payment_event():void { + $o=$this->order(['status'=>0,'paid_at'=>null]);DB::beginTransaction();$this->assertTrue((new OrderService($o))->paid('cb'));Bus::assertNotDispatched(DeliverOrderReport::class);DB::rollBack();$this->assertSame(0,OrderReportEvent::count());$this->assertSame(0,(int)$o->fresh()->status);Bus::assertNotDispatched(DeliverOrderReport::class);Http::assertNothingSent(); + } + public function test_missing_outbox_does_not_break_payment_and_scan_recovers_it_later():void { + Schema::drop('v2_order_report_events');$o=$this->order(['status'=>0,'paid_at'=>null]);$this->assertTrue((new OrderService($o))->paid('cb'));$this->assertSame(1,(int)$o->fresh()->status);$this->migrate();$this->assertSame(1,app(Reporter::class)->reconcile());$this->assertSame(1,OrderReportEvent::where('kind','payment')->count());Http::assertNothingSent(); + } + public function test_queue_failure_cannot_reverse_payment_and_outbox_remains_recoverable():void { + $reporter=new class extends Reporter {public function queue(int $id):void {throw new \RuntimeException('simulated queue failure');}};$this->app->instance(Reporter::class,$reporter);$o=$this->order(['status'=>0,'paid_at'=>null]);$this->assertTrue((new OrderService($o))->paid('cb'));$this->assertSame(1,(int)$o->fresh()->status);$this->assertSame('pending',OrderReportEvent::where('kind','payment')->first()->status);Http::assertNothingSent(); + } + public function test_capture_freezes_amounts_and_never_includes_private_payment_values():void { + $o=$this->order();$s=app(Reporter::class);$e=$s->capture($o);$payload=$e->payload;$this->assertSame(1250,$payload['facts']['total_cents']);$this->assertSame(1050,$payload['facts']['gateway_cents']);$this->assertStringNotContainsString($o->trade_no,$payload['text']);$this->assertStringNotContainsString('secret-order-key',$payload['text']);$o->update(['total_amount'=>99999]);$this->assertSame($payload,$s->capture($o)->payload); + } + public function test_daily_boundary_status_balance_fee_and_zero_rules():void { + foreach([['2026-10-31 07:59:59',1,1000,0,0],['2026-10-31 08:00:00',1,1000,200,50],['2026-11-01 07:59:59',3,0,500,0],['2026-10-31 12:00:00',4,0,0,90],['2026-11-01 08:00:00',1,9999,0,0],['2026-10-31 13:00:00',0,8888,0,0],['2026-10-31 14:00:00',2,7777,0,0]] as [$t,$status,$cash,$balance,$fee])$this->order(['paid_at'=>CarbonImmutable::parse($t,'Asia/Shanghai')->timestamp,'status'=>$status,'total_amount'=>$cash,'balance_amount'=>$balance,'handling_amount'=>$fee]); + $e=app(Reporter::class)->daily();$f=$e->payload['facts'];$this->assertSame(2,$f['paid_count']);$this->assertSame(1,$f['zero_count']);$this->assertSame(1750,$f['total_cents']);$this->assertSame(1050,$f['gateway_cents']);$this->assertSame(700,$f['balance_cents']);$this->assertSame(86400,$f['end_at']-$f['start_at']);$this->assertSame('info',$e->bot);$this->assertStringContainsString('2026-10-31 08:00–2026-11-01 08:00',$e->payload['text']); + } + public function test_daily_is_immutable_and_zero_days_are_reported():void { + $s=app(Reporter::class);$e=$s->daily();$this->assertSame(0,$e->payload['facts']['paid_count']);$payload=$e->payload;$this->order(['paid_at'=>now()->subHours(7)->timestamp]);$this->assertSame($e->id,$s->daily()->id);$this->assertSame($payload,$s->daily()->payload); + } + public function test_no_daily_is_created_before_eight_and_timezone_is_explicit():void { + config(['app.timezone'=>'UTC']);$s=app(Reporter::class);$this->assertNull($s->daily(CarbonImmutable::parse('2026-11-01 07:59:59','Asia/Shanghai')));$this->assertNotNull($s->daily(CarbonImmutable::parse('2026-11-01 08:00:00','Asia/Shanghai'))); + } + public function test_history_is_not_replayed_but_a_late_paid_old_order_is_recovered():void { + $s=app(Reporter::class);$old=$this->order(['paid_at'=>now()->subMonth()->timestamp]);$s->initialize();$this->order();$this->assertSame(1,$s->reconcile());$this->assertSame(0,$s->reconcile());$old->update(['paid_at'=>now()->timestamp]);$this->assertSame(1,$s->reconcile());$this->assertSame(2,OrderReportEvent::where('kind','payment')->count()); + } + public function test_daily_still_counts_complete_period_before_activation():void { + $this->order(['paid_at'=>CarbonImmutable::parse('2026-10-31 10:00','Asia/Shanghai')->timestamp]);$s=app(Reporter::class);$this->assertSame(0,$s->reconcile());$this->assertSame(1,$s->daily()->payload['facts']['paid_count']); + } + public function test_command_only_queues_and_never_sends_http_inline():void { + $this->order();$this->artisan('orders:report-payments')->assertExitCode(0);Bus::assertDispatched(DeliverOrderReport::class,2);Http::assertNothingSent(); + } + public function test_same_job_is_throttled_before_worker_claim():void { + $e=$this->event();$s=app(Reporter::class);$s->queue($e->id);$s->queue($e->id);Bus::assertDispatched(DeliverOrderReport::class,1);Http::assertNothingSent(); + } + public function test_post_then_only_get_original_receipt_and_sent_is_terminal():void { + Http::fake(['*/api/v1/messages*'=>fn($q)=>$this->response($q->method()==='GET'?'sent':'queued',$q->method()==='GET'?200:202)]);$s=app(Reporter::class);$e=$this->event();$s->deliver($e->id);$this->assertSame('queued',$e->fresh()->status);$this->travel(6)->minutes();$s->deliver($e->id);$s->deliver($e->id);$this->assertSame('sent',$e->fresh()->status);$this->assertCount(1,Http::recorded(fn($q)=>$q->method()==='POST'));$this->assertCount(1,Http::recorded(fn($q)=>$q->method()==='GET'));Http::assertSent(fn($q)=>$q->method()==='POST'&&$q['bot']==='log'&&$q['target']==='base'); + } + public function test_daily_job_uses_info():void { + Http::fake(['*/api/v1/messages'=>fn()=>$this->response('sent')]);$e=app(Reporter::class)->daily();(new DeliverOrderReport($e->id))->handle(app(Reporter::class));Http::assertSent(fn($q)=>$q['bot']==='info');$this->assertSame('sent',$e->fresh()->status); + } + public function test_transport_unknown_retries_same_frozen_key_and_text():void { + $fail=true;Http::fake(['*/api/v1/messages'=>function()use(&$fail){if($fail)throw new \Illuminate\Http\Client\ConnectionException('simulated');return $this->response();}]);$s=app(Reporter::class);$e=$this->event();$s->deliver($e->id);$this->assertSame('telehub_transport_unknown',$e->fresh()->error_code);$this->travel(6)->minutes();$fail=false;$s->deliver($e->id);Http::assertSent(fn($q)=>$q->hasHeader('Idempotency-Key',$e->business_key)&&$q['text']===$e->payload['text']);$this->assertSame('queued',$e->fresh()->status); + } + public function test_lease_blocks_concurrent_worker_and_recovers_after_expiry():void { + Http::fake(['*/api/v1/messages'=>fn()=>$this->response()]);$e=$this->event();$e->update(['lease_until'=>now()->timestamp+60]);$s=app(Reporter::class);$s->deliver($e->id);Http::assertNothingSent();$this->travel(61)->seconds();$s->deliver($e->id);Http::assertSentCount(1); + } + public function test_permission_rejection_stops_without_fallback():void { + Http::fake(['*'=>Http::response([],403)]);$s=app(Reporter::class);$e=$this->event();$s->deliver($e->id);$this->travel(1)->hours();$s->deliver($e->id);$this->assertSame('failed',$e->fresh()->status);$this->assertSame('telehub_http_403',$e->fresh()->error_code);Http::assertSentCount(1); + } + public function test_rate_limit_obeys_retry_after_with_same_event():void { + Http::fake(['*'=>Http::sequence()->push([],429,['Retry-After'=>'900'])->push(['data'=>['id'=>self::UUID,'status'=>'queued']],202)]);$s=app(Reporter::class);$e=$this->event();$s->deliver($e->id);$this->travel(6)->minutes();$s->deliver($e->id);Http::assertSentCount(1);$this->travel(10)->minutes();$s->deliver($e->id);$this->assertSame('queued',$e->fresh()->status);Http::assertSentCount(2); + } + public function test_uncertain_failed_cancelled_are_terminal():void { + $status='uncertain';Http::fake(['*'=>function()use(&$status){return $this->response($status);}]);$s=app(Reporter::class);foreach(['uncertain','failed','cancelled'] as $value){$status=$value;$e=$this->event();$s->deliver($e->id);$this->travel(6)->minutes();$s->deliver($e->id);$this->assertSame($value,$e->fresh()->status);}Http::assertSentCount(3); + } + public function test_receipt_mismatch_cannot_change_saved_receipt():void { + Http::fake(['*'=>fn($q)=>Http::response(['data'=>['id'=>$q->method()==='GET'?'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa':self::UUID,'status'=>'queued']],200)]);$s=app(Reporter::class);$e=$this->event();$s->deliver($e->id);$this->travel(6)->minutes();$s->deliver($e->id);$this->assertSame(self::UUID,$e->fresh()->receipt_id);$this->assertSame('telehub_response_invalid',$e->fresh()->error_code); + } + public function test_corrupted_event_is_blocked_without_retrying_or_sending():void { + $s=app(Reporter::class);$e=$this->event();$payload=$e->payload;$payload['bot']='base';$e->update(['payload'=>$payload]);$s->deliver($e->id);$this->assertSame('failed',$e->fresh()->status);$this->assertSame('event_invalid',$e->fresh()->error_code);$this->assertSame(0,$s->queueDue());Http::assertNothingSent(); + } + public function test_missing_key_and_foreign_identity_never_send():void { + $s=app(Reporter::class);$e=$this->event();config(['order_report.telehub_key'=>'']);$s->deliver($e->id);$this->assertSame('telehub_configuration_required',$e->fresh()->error_code);config(['order_report.telehub_key'=>'key','order_report.project'=>'HN']);$s->deliver($e->id);Http::assertNothingSent(); + } + public function test_flags_and_nonproduction_stop_capture_queue_and_delivery():void { + $s=app(Reporter::class);$e=$this->event();config(['order_report.payment_enabled'=>false]);$s->deliver($e->id);$this->assertNull($s->capture($this->order()));config(['order_report.daily_enabled'=>false]);$this->assertNull($s->daily());config(['order_report.payment_enabled'=>true,'app.env'=>'local']);$this->assertNull($s->capture($this->order()));$this->assertSame(0,$s->queueDue());$s->deliver($e->id);Http::assertNothingSent(); + } + public function test_features_default_on_for_new_instances():void { + $config=require base_path('config/order_report.php');$this->assertTrue($config['enabled']);$this->assertTrue($config['payment_enabled']);$this->assertTrue($config['daily_enabled']); + } + public function test_daily_and_retry_schedule_are_registered():void { + $events=collect(app(\Illuminate\Console\Scheduling\Schedule::class)->events())->filter(fn($e)=>str_contains($e->command??'','orders:report-payments'));$this->assertCount(2,$events);$this->assertSame(['* * * * *','0 8 * * *'],$events->pluck('expression')->values()->all());$this->assertSame('Asia/Shanghai',$events->last()->timezone); + } +}