Files
dpl/tests/Feature/OrderReporting/OrderReportingTest.php
T

108 lines
15 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace Tests\Feature\OrderReporting;
use App\Jobs\{DeliverOrderReport,OrderHandleJob};
use App\Models\{Order,OrderReportEvent};
use App\Services\{OrderService,OrderReporting\Reporter};
use Carbon\CarbonImmutable;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\{Bus,Cache,DB,Http,Schema};
use Tests\TestCase;
class OrderReportingTest extends TestCase
{
private const UUID='12345678-1234-1234-1234-123456789abc';
protected function setUp():void {
parent::setUp();config(['database.default'=>'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);
}
}