feat: 拆分开奖与结算审核流程,新增手动结果录入、重开和派彩审批接口

This commit is contained in:
2026-05-16 18:01:06 +08:00
parent 83046b402d
commit 4f143c7cb1
38 changed files with 1992 additions and 170 deletions

View File

@@ -2,6 +2,7 @@
use Carbon\Carbon;
use App\Models\Draw;
use App\Models\AdminRole;
use App\Models\AdminUser;
use App\Lottery\DrawStatus;
use App\Models\DrawResultItem;
@@ -46,6 +47,151 @@ test('draw planner fills buffer rows with ordered draw_no', function (): void {
expect($drawNos)->toEqual($sorted);
});
test('admin can batch generate draw schedule buffer', function (): void {
Carbon::setTestNow(Carbon::parse('2026-05-09 12:00:00', 'UTC'));
$admin = AdminUser::query()->create([
'username' => 'draw_plan_admin',
'name' => 'Draw Plan Admin',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
grantSuperAdminRole($admin);
$token = $admin->createToken('test', ['*'], now()->addDay())->plainTextToken;
$this->withHeader('Authorization', 'Bearer '.$token)
->postJson('/api/v1/admin/draws/generate-plan')
->assertOk()
->assertJsonPath('data.buffer_target', 3);
expect(Draw::query()->count())->toBeGreaterThanOrEqual(3);
Carbon::setTestNow();
});
test('admin can manually close open draw', function (): void {
Carbon::setTestNow(Carbon::parse('2026-05-09 12:10:00', 'UTC'));
$draw = Draw::query()->create([
'draw_no' => '20260509-120',
'business_date' => '2026-05-09',
'sequence_no' => 120,
'status' => DrawStatus::Open->value,
'start_time' => now()->copy()->subMinute(),
'close_time' => now()->copy()->addMinutes(10),
'draw_time' => now()->copy()->addMinutes(15),
'cooling_end_time' => null,
'result_source' => null,
'current_result_version' => 0,
'settle_version' => 0,
'is_reopened' => false,
]);
$admin = AdminUser::query()->create([
'username' => 'draw_close_admin',
'name' => 'Draw Close Admin',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
grantSuperAdminRole($admin);
$token = $admin->createToken('test', ['*'], now()->addDay())->plainTextToken;
$this->withHeader('Authorization', 'Bearer '.$token)
->postJson("/api/v1/admin/draws/{$draw->id}/manual-close")
->assertOk()
->assertJsonPath('data.status', DrawStatus::Closing->value);
$draw->refresh();
expect($draw->status)->toBe(DrawStatus::Closing->value);
expect($draw->close_time?->timestamp)->toBe(now()->timestamp);
Carbon::setTestNow();
});
test('admin can cancel draw before results exist', function (): void {
Carbon::setTestNow(Carbon::parse('2026-05-09 12:15:00', 'UTC'));
$draw = Draw::query()->create([
'draw_no' => '20260509-121',
'business_date' => '2026-05-09',
'sequence_no' => 121,
'status' => DrawStatus::Pending->value,
'start_time' => now()->copy()->addMinute(),
'close_time' => now()->copy()->addMinutes(10),
'draw_time' => now()->copy()->addMinutes(15),
'cooling_end_time' => null,
'result_source' => null,
'current_result_version' => 0,
'settle_version' => 0,
'is_reopened' => false,
]);
$admin = AdminUser::query()->create([
'username' => 'draw_cancel_admin',
'name' => 'Draw Cancel Admin',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
grantSuperAdminRole($admin);
$token = $admin->createToken('test', ['*'], now()->addDay())->plainTextToken;
$this->withHeader('Authorization', 'Bearer '.$token)
->postJson("/api/v1/admin/draws/{$draw->id}/cancel")
->assertOk()
->assertJsonPath('data.status', DrawStatus::Cancelled->value);
$draw->refresh();
expect($draw->status)->toBe(DrawStatus::Cancelled->value);
Carbon::setTestNow();
});
test('admin can manually trigger rng for closed draw', function (): void {
config(['lottery.draw.require_manual_review' => true]);
Carbon::setTestNow(Carbon::parse('2026-05-09 12:20:00', 'UTC'));
$draw = Draw::query()->create([
'draw_no' => '20260509-122',
'business_date' => '2026-05-09',
'sequence_no' => 122,
'status' => DrawStatus::Closed->value,
'start_time' => now()->copy()->subMinutes(20),
'close_time' => now()->copy()->subMinutes(5),
'draw_time' => now()->copy()->subMinute(),
'cooling_end_time' => null,
'result_source' => null,
'current_result_version' => 0,
'settle_version' => 0,
'is_reopened' => false,
]);
$admin = AdminUser::query()->create([
'username' => 'draw_rng_admin',
'name' => 'Draw Rng Admin',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
grantSuperAdminRole($admin);
$token = $admin->createToken('test', ['*'], now()->addDay())->plainTextToken;
$this->withHeader('Authorization', 'Bearer '.$token)
->postJson("/api/v1/admin/draws/{$draw->id}/rng")
->assertOk()
->assertJsonPath('data.status', DrawStatus::Review->value)
->assertJsonPath('data.batch.source_type', 'rng')
->assertJsonPath('data.batch.items_count', 23);
$draw->refresh();
expect($draw->status)->toBe(DrawStatus::Review->value);
expect(DrawResultBatch::query()->where('draw_id', $draw->id)->count())->toBe(1);
Carbon::setTestNow();
});
test('draw tick moves open draw to closing when close_time passed before draw_time', function (): void {
Carbon::setTestNow(Carbon::parse('2026-05-09 14:00:00', 'UTC'));
@@ -167,6 +313,191 @@ test('draw tick rng awaits manual publish when review enabled', function (): voi
Carbon::setTestNow();
});
test('admin can create manual result batch with 23 numbers for review', function (): void {
Carbon::setTestNow(Carbon::parse('2026-05-09 14:20:00', 'UTC'));
$draw = Draw::query()->create([
'draw_no' => '20260509-220',
'business_date' => '2026-05-09',
'sequence_no' => 220,
'status' => DrawStatus::Closed->value,
'start_time' => now()->copy()->subMinutes(20),
'close_time' => now()->copy()->subMinutes(2),
'draw_time' => now()->copy()->subMinute(),
'cooling_end_time' => null,
'result_source' => null,
'current_result_version' => 0,
'settle_version' => 0,
'is_reopened' => false,
]);
$admin = AdminUser::query()->create([
'username' => 'manual_draw_admin',
'name' => 'Manual Draw Admin',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
grantSuperAdminRole($admin);
$token = $admin->createToken('test', ['*'], now()->addDay())->plainTextToken;
$items = [];
foreach (array_values(App\Services\Draw\DrawPrizeLayout::slots()) as $i => $slot) {
$items[] = [
'prize_type' => $slot['prize_type'],
'prize_index' => $slot['prize_index'],
'number_4d' => str_pad((string) ($i + 1), 4, '0', STR_PAD_LEFT),
];
}
$this->withHeader('Authorization', 'Bearer '.$token)
->postJson("/api/v1/admin/draws/{$draw->id}/result-batches", ['items' => $items])
->assertOk()
->assertJsonPath('data.draw_no', '20260509-220')
->assertJsonPath('data.status', DrawStatus::Review->value)
->assertJsonPath('data.batch.status', DrawResultBatchStatus::PendingReview->value)
->assertJsonPath('data.batch.source_type', 'manual')
->assertJsonPath('data.batch.items_count', 23);
$draw->refresh();
expect($draw->status)->toBe(DrawStatus::Review->value);
expect($draw->result_source)->toBe('manual');
expect(DrawResultBatch::query()->where('draw_id', $draw->id)->where('source_type', 'manual')->count())->toBe(1);
expect(DrawResultItem::query()->where('draw_id', $draw->id)->count())->toBe(23);
Carbon::setTestNow();
});
test('admin can reopen cooldown draw for a replacement result batch', function (): void {
Carbon::setTestNow(Carbon::parse('2026-05-09 14:30:00', 'UTC'));
$draw = Draw::query()->create([
'draw_no' => '20260509-230',
'business_date' => '2026-05-09',
'sequence_no' => 230,
'status' => DrawStatus::Cooldown->value,
'start_time' => now()->copy()->subMinutes(20),
'close_time' => now()->copy()->subMinutes(3),
'draw_time' => now()->copy()->subMinutes(2),
'cooling_end_time' => now()->copy()->addMinutes(10),
'result_source' => 'rng',
'current_result_version' => 1,
'settle_version' => 0,
'is_reopened' => false,
]);
$batch = DrawResultBatch::query()->create([
'draw_id' => $draw->id,
'result_version' => 1,
'source_type' => 'rng',
'rng_seed_hash' => hash('sha256', 'seed'),
'raw_seed_encrypted' => null,
'status' => DrawResultBatchStatus::Published->value,
'created_by' => null,
'confirmed_by' => null,
'confirmed_at' => now(),
]);
foreach (App\Services\Draw\DrawPrizeLayout::slots() as $i => $slot) {
$number = str_pad((string) ($i + 100), 4, '0', STR_PAD_LEFT);
DrawResultItem::query()->create([
'draw_id' => $draw->id,
'result_batch_id' => $batch->id,
'prize_type' => $slot['prize_type'],
'prize_index' => $slot['prize_index'],
'number_4d' => $number,
'suffix_3d' => substr($number, -3),
'suffix_2d' => substr($number, -2),
'head_digit' => (int) substr($number, 0, 1),
'tail_digit' => (int) substr($number, 3, 1),
]);
}
$admin = AdminUser::query()->create([
'username' => 'reopen_draw_admin',
'name' => 'Reopen Draw Admin',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
grantSuperAdminRole($admin);
$token = $admin->createToken('test', ['*'], now()->addDay())->plainTextToken;
$this->withHeader('Authorization', 'Bearer '.$token)
->postJson("/api/v1/admin/draws/{$draw->id}/reopen", ['reason' => 'wrong result'])
->assertOk()
->assertJsonPath('data.draw_no', '20260509-230')
->assertJsonPath('data.status', DrawStatus::Closed->value)
->assertJsonPath('data.is_reopened', true)
->assertJsonPath('data.current_result_version', 1);
$draw->refresh();
expect($draw->status)->toBe(DrawStatus::Closed->value);
expect($draw->is_reopened)->toBeTrue();
expect($draw->cooling_end_time)->toBeNull();
Carbon::setTestNow();
});
test('non super admin cannot reopen cooldown draw', function (): void {
Carbon::setTestNow(Carbon::parse('2026-05-09 14:35:00', 'UTC'));
$draw = Draw::query()->create([
'draw_no' => '20260509-231',
'business_date' => '2026-05-09',
'sequence_no' => 231,
'status' => DrawStatus::Cooldown->value,
'start_time' => now()->copy()->subMinutes(20),
'close_time' => now()->copy()->subMinutes(3),
'draw_time' => now()->copy()->subMinutes(2),
'cooling_end_time' => now()->copy()->addMinutes(10),
'result_source' => 'rng',
'current_result_version' => 1,
'settle_version' => 0,
'is_reopened' => false,
]);
$role = AdminRole::query()->create([
'slug' => 'draw_manager_test',
'name' => 'Draw Manager Test',
]);
$ids = DB::table('admin_menu_actions')
->whereIn('permission_code', App\Support\AdminPermissionBridge::menuActionCodesForLegacy('prd.draw_result.manage'))
->where('status', 1)
->pluck('id');
foreach ($ids as $mid) {
DB::table('admin_role_menu_actions')->insert([
'role_id' => $role->id,
'menu_action_id' => (int) $mid,
]);
}
$admin = AdminUser::query()->create([
'username' => 'draw_manager_only',
'name' => 'Draw Manager Only',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
$admin->roles()->sync([
(int) $role->id => [
'site_id' => AdminUser::defaultAdminSiteId(),
'granted_at' => now(),
],
]);
$token = $admin->createToken('test', ['*'], now()->addDay())->plainTextToken;
$this->withHeader('Authorization', 'Bearer '.$token)
->postJson("/api/v1/admin/draws/{$draw->id}/reopen")
->assertStatus(403);
$draw->refresh();
expect($draw->status)->toBe(DrawStatus::Cooldown->value);
expect($draw->is_reopened)->toBeFalse();
Carbon::setTestNow();
});
test('cooldown expiry tick moves draw to settling', function (): void {
config([
'lottery.draw.require_manual_review' => false,
@@ -201,9 +532,9 @@ test('cooldown expiry tick moves draw to settling', function (): void {
app(DrawTickService::class)->tick(now()->utc());
$draw->refresh();
expect($draw->status)->toBe(DrawStatus::Settled->value);
expect($draw->status)->toBe(DrawStatus::Settling->value);
expect((int) $draw->settle_version)->toBe(1);
expect(SettlementBatch::query()->where('draw_id', $draw->id)->where('status', 'completed')->count())->toBe(1);
expect(SettlementBatch::query()->where('draw_id', $draw->id)->where('status', 'pending_review')->count())->toBe(1);
Carbon::setTestNow();
});
@@ -231,10 +562,10 @@ test('GET draw current returns open draw with seconds to close', function (): vo
$this->getJson('/api/v1/draw/current')
->assertOk()
->assertJsonPath('data.draw_no', '20260509-300')
->assertJsonPath('data.status', DrawStatus::Open->value)
->assertJsonPath('data.seconds_to_close', 60 * 60 - 30)
->assertJsonPath('data.seconds_to_draw', 3600);
->assertJsonPath('data.data.draw_no', '20260509-300')
->assertJsonPath('data.data.status', DrawStatus::Open->value)
->assertJsonPath('data.data.seconds_to_close', 60 * 60 - 30)
->assertJsonPath('data.data.seconds_to_draw', 3600);
Carbon::setTestNow();
});
@@ -261,10 +592,10 @@ test('GET draw current exposes closing when row is open in DB but close_time has
$this->getJson('/api/v1/draw/current')
->assertOk()
->assertJsonPath('data.draw_no', '20260509-310')
->assertJsonPath('data.status', DrawStatus::Closing->value)
->assertJsonPath('data.seconds_to_close', 0)
->assertJsonPath('data.seconds_to_draw', 20);
->assertJsonPath('data.data.draw_no', '20260509-310')
->assertJsonPath('data.data.status', DrawStatus::Closing->value)
->assertJsonPath('data.data.seconds_to_close', 0)
->assertJsonPath('data.data.seconds_to_draw', 20);
Carbon::setTestNow();
});
@@ -291,10 +622,10 @@ test('GET draw current exposes closed when row is open in DB but draw_time has p
$this->getJson('/api/v1/draw/current')
->assertOk()
->assertJsonPath('data.draw_no', '20260509-311')
->assertJsonPath('data.status', DrawStatus::Closed->value)
->assertJsonPath('data.seconds_to_close', 0)
->assertJsonPath('data.seconds_to_draw', 0);
->assertJsonPath('data.data.draw_no', '20260509-311')
->assertJsonPath('data.data.status', DrawStatus::Closed->value)
->assertJsonPath('data.data.seconds_to_close', 0)
->assertJsonPath('data.data.seconds_to_draw', 0);
Carbon::setTestNow();
});
@@ -343,8 +674,8 @@ test('GET draw current includes result_items when cooldown', function (): void {
$this->getJson('/api/v1/draw/current')
->assertOk()
->assertJsonPath('data.status', DrawStatus::Cooldown->value)
->assertJsonPath('data.result_items.0.number_4d', '1234');
->assertJsonPath('data.data.status', DrawStatus::Cooldown->value)
->assertJsonPath('data.data.result_items.0.number_4d', '1234');
Carbon::setTestNow();
});

View File

@@ -2,6 +2,7 @@
use App\Models\Draw;
use App\Models\Player;
use App\Models\AdminUser;
use App\Models\TicketItem;
use App\Lottery\DrawStatus;
use App\Models\JackpotPool;
@@ -10,7 +11,9 @@ use App\Models\PlayerWallet;
use App\Models\DrawResultItem;
use App\Models\DrawResultBatch;
use App\Models\JackpotPayoutLog;
use App\Models\SettlementBatch;
use App\Models\JackpotContribution;
use Illuminate\Support\Facades\Hash;
use Database\Seeders\CurrencySeeder;
use Database\Seeders\PlayTypeSeeder;
use App\Lottery\DrawResultBatchStatus;
@@ -19,6 +22,7 @@ use Database\Seeders\LotterySettingsSeeder;
use Database\Seeders\OperationalConfigV1Seeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Services\Settlement\SettlementOrchestrator;
use App\Services\Settlement\SettlementBatchWorkflowService;
uses(RefreshDatabase::class);
@@ -128,6 +132,18 @@ test('jackpot contributes on place and bursts on settle for first-prize straight
$ran = app(SettlementOrchestrator::class)->trySettleDraw($draw->fresh());
expect($ran)->toBeTrue();
$admin = AdminUser::query()->create([
'username' => 'jp_settle_admin',
'name' => 'JP Settle Admin',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
grantSuperAdminRole($admin);
$settlementBatch = SettlementBatch::query()->where('draw_id', $draw->id)->firstOrFail();
app(SettlementBatchWorkflowService::class)->approve($settlementBatch, $admin);
app(SettlementBatchWorkflowService::class)->payout($settlementBatch->fresh());
$item = TicketItem::query()->where('draw_id', $draw->id)->firstOrFail();
expect((int) $item->win_amount)->toBe(250_000);
expect((int) $item->jackpot_win_amount)->toBe(1_000);

View File

@@ -10,6 +10,8 @@ use App\Models\PlayerWallet;
use App\Models\DrawResultItem;
use App\Models\DrawResultBatch;
use App\Models\SettlementBatch;
use App\Models\AdminUser;
use Illuminate\Support\Facades\Hash;
use Database\Seeders\CurrencySeeder;
use Database\Seeders\PlayTypeSeeder;
use App\Lottery\DrawResultBatchStatus;
@@ -18,6 +20,7 @@ use Database\Seeders\LotterySettingsSeeder;
use Database\Seeders\OperationalConfigV1Seeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Services\Settlement\SettlementOrchestrator;
use App\Services\Settlement\SettlementBatchWorkflowService;
uses(RefreshDatabase::class);
@@ -111,6 +114,18 @@ test('settlement pays big winner and marks ticket settled', function (): void {
$ran = app(SettlementOrchestrator::class)->trySettleDraw($draw->fresh());
expect($ran)->toBeTrue();
$admin = AdminUser::query()->create([
'username' => 'settlement_legacy_reviewer',
'name' => 'Settlement Legacy Reviewer',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
grantSuperAdminRole($admin);
$settlementBatch = SettlementBatch::query()->where('draw_id', $draw->id)->firstOrFail();
app(SettlementBatchWorkflowService::class)->approve($settlementBatch, $admin);
app(SettlementBatchWorkflowService::class)->payout($settlementBatch->fresh());
$draw->refresh();
expect($draw->status)->toBe(DrawStatus::Settled->value);
expect((int) $draw->settle_version)->toBe(1);
@@ -129,3 +144,123 @@ test('settlement pays big winner and marks ticket settled', function (): void {
expect(WalletTxn::query()->where('biz_type', 'settle_payout')->count())->toBe(1);
});
test('admin settlement requires review before payout and can export report', function (): void {
$uniq = bin2hex(random_bytes(4));
$player = Player::query()->create([
'site_code' => 'test',
'site_player_id' => 'settle-review-p-'.$uniq,
'username' => 'srp_'.$uniq,
'nickname' => null,
'default_currency' => 'NPR',
'status' => 0,
]);
PlayerWallet::query()->create([
'player_id' => $player->id,
'wallet_type' => 'lottery',
'currency_code' => 'NPR',
'balance' => 5_000_000,
'frozen_balance' => 0,
'status' => 0,
'version' => 0,
]);
$draw = Draw::query()->create([
'draw_no' => '20260511-901',
'business_date' => '2026-05-11',
'sequence_no' => 901,
'status' => DrawStatus::Open->value,
'start_time' => now()->subMinutes(2),
'close_time' => now()->addMinutes(5),
'draw_time' => now()->addMinutes(6),
'cooling_end_time' => null,
'result_source' => null,
'current_result_version' => 0,
'settle_version' => 0,
'is_reopened' => false,
]);
$this->withHeader('Authorization', 'Bearer dev:'.$player->id)
->postJson('/api/v1/ticket/place', [
'draw_id' => '20260511-901',
'currency_code' => 'NPR',
'client_trace_id' => 'settle-review-trace-1',
'lines' => [
['number' => '1234', 'play_code' => 'big', 'amount' => 10_000],
],
])
->assertOk();
$batch = DrawResultBatch::query()->create([
'draw_id' => $draw->id,
'result_version' => 1,
'source_type' => 'rng',
'rng_seed_hash' => 'review-test',
'raw_seed_encrypted' => null,
'status' => DrawResultBatchStatus::Published->value,
'created_by' => null,
'confirmed_by' => null,
'confirmed_at' => now(),
]);
foreach (DrawPrizeLayout::slots() as $slot) {
$num = $slot['prize_type'] === 'first' ? '1234' : '5678';
DrawResultItem::query()->create([
'draw_id' => $draw->id,
'result_batch_id' => $batch->id,
'prize_type' => $slot['prize_type'],
'prize_index' => $slot['prize_index'],
'number_4d' => $num,
'suffix_3d' => substr($num, -3),
'suffix_2d' => substr($num, -2),
'head_digit' => (int) substr($num, 0, 1),
'tail_digit' => (int) substr($num, 3, 1),
]);
}
$draw->forceFill([
'status' => DrawStatus::Settling->value,
'current_result_version' => 1,
])->save();
$admin = AdminUser::query()->create([
'username' => 'settlement_reviewer',
'name' => 'Settlement Reviewer',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
grantSuperAdminRole($admin);
$token = $admin->createToken('test', ['*'], now()->addDay())->plainTextToken;
$this->withHeader('Authorization', 'Bearer '.$token)
->postJson("/api/v1/admin/draws/{$draw->id}/settlement/run")
->assertOk()
->assertJsonPath('data.status', DrawStatus::Settling->value);
$settlement = SettlementBatch::query()->where('draw_id', $draw->id)->firstOrFail();
expect($settlement->status)->toBe('pending_review');
$item = TicketItem::query()->where('draw_id', $draw->id)->firstOrFail();
expect($item->status)->toBe('pending_payout');
expect(WalletTxn::query()->where('biz_type', 'settle_payout')->count())->toBe(0);
$this->withHeader('Authorization', 'Bearer '.$token)
->postJson("/api/v1/admin/settlement-batches/{$settlement->id}/approve")
->assertOk()
->assertJsonPath('data.review_status', 'approved');
$this->withHeader('Authorization', 'Bearer '.$token)
->postJson("/api/v1/admin/settlement-batches/{$settlement->id}/payout")
->assertOk()
->assertJsonPath('data.status', 'paid');
$item->refresh();
expect($item->status)->toBe('settled_win');
expect(WalletTxn::query()->where('biz_type', 'settle_payout')->count())->toBe(1);
$this->withHeader('Authorization', 'Bearer '.$token)
->get("/api/v1/admin/settlement-batches/{$settlement->id}/export")
->assertOk()
->assertHeader('content-type', 'text/csv; charset=UTF-8');
});

View File

@@ -6,6 +6,7 @@
use App\Models\Draw;
use App\Models\Player;
use App\Models\AdminUser;
use App\Models\RiskPool;
use App\Models\WalletTxn;
use App\Lottery\ErrorCode;
@@ -17,6 +18,7 @@ use App\Models\PlayerWallet;
use App\Models\DrawResultItem;
use App\Models\DrawResultBatch;
use App\Models\JackpotPayoutLog;
use App\Models\SettlementBatch;
use App\Models\TicketCombination;
use App\Models\JackpotContribution;
use App\Support\OddsStandardScopes;
@@ -24,7 +26,9 @@ use Database\Seeders\CurrencySeeder;
use Database\Seeders\PlayTypeSeeder;
use App\Lottery\DrawResultBatchStatus;
use App\Models\TicketSettlementDetail;
use App\Services\Settlement\SettlementBatchWorkflowService;
use App\Services\Draw\DrawPrizeLayout;
use Illuminate\Support\Facades\Hash;
use Database\Seeders\LotterySettingsSeeder;
use Database\Seeders\OperationalConfigV1Seeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
@@ -135,6 +139,22 @@ function p145_board_without_8888(string $prizeType, int $prizeIndex): string
};
}
function p145_approve_and_payout(Draw $draw): void
{
$batch = SettlementBatch::query()->where('draw_id', $draw->id)->latest('id')->firstOrFail();
$admin = AdminUser::query()->create([
'username' => 'p145_settle_'.bin2hex(random_bytes(3)),
'name' => 'P145 Settlement',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
grantSuperAdminRole($admin);
$workflow = app(SettlementBatchWorkflowService::class);
$workflow->approve($batch, $admin);
$workflow->payout($batch->fresh());
}
test('§14.5 big no-hit settles lose wallet unchanged except bet and no settle_payout txn', function (): void {
$player = p145_player();
$drawNo = p145_next_draw_no();
@@ -161,6 +181,7 @@ test('§14.5 big no-hit settles lose wallet unchanged except bet and no settle_p
])->save();
expect(app(SettlementOrchestrator::class)->trySettleDraw($draw->fresh()))->toBeTrue();
p145_approve_and_payout($draw);
$item->refresh();
expect($item->status)->toBe('settled_lose')
@@ -224,6 +245,7 @@ test('§14.5 small hits second tier only', function (): void {
])->save();
expect(app(SettlementOrchestrator::class)->trySettleDraw($draw->fresh()))->toBeTrue();
p145_approve_and_payout($draw);
$item->refresh();
expect($item->status)->toBe('settled_win')
@@ -300,11 +322,7 @@ test('§14.5 pos_4b pos_3a pos_2a pos_4e each settle with expected win', functio
$deduct = (int) $item->actual_deduct_amount;
$odds = OddsStandardScopes::PRESET_ODDS_BY_SCOPE[$case['scope']];
$perComboWin = (int) floor(10_000 * $odds / 10_000);
$comboCount = (int) $item->combination_count;
$expectedWin = match ($case['play']) {
'pos_3a', 'pos_2a' => $perComboWin * $comboCount,
default => $perComboWin,
};
$expectedWin = $perComboWin;
p145_publish_board($draw, $case['board']);
$draw->forceFill([
@@ -313,6 +331,7 @@ test('§14.5 pos_4b pos_3a pos_2a pos_4e each settle with expected win', functio
])->save();
expect(app(SettlementOrchestrator::class)->trySettleDraw($draw->fresh()))->toBeTrue();
p145_approve_and_payout($draw);
$item->refresh();
expect($item->status)->toBe('settled_win', $case['play'])
@@ -323,6 +342,77 @@ test('§14.5 pos_4b pos_3a pos_2a pos_4e each settle with expected win', functio
}
});
test('module 6 suffix plays settle once per ticket item instead of once per expanded prefix', function (): void {
$cases = [
[
'play' => 'pos_3a',
'number' => '234',
'board' => fn (string $t, int $i): string => $t === 'first' ? '1234' : p145_board_without_8888($t, $i),
'scope' => 'first',
],
[
'play' => 'pos_2a',
'number' => '34',
'board' => fn (string $t, int $i): string => $t === 'first' ? '1234' : p145_board_without_8888($t, $i),
'scope' => 'first',
],
[
'play' => 'pos_3abc',
'number' => '567',
'board' => fn (string $t, int $i): string => match ($t) {
'first' => '4567',
default => p145_board_without_8888($t, $i),
},
'scope' => 'first',
],
[
'play' => 'pos_2abc',
'number' => '99',
'board' => fn (string $t, int $i): string => match ($t) {
'first' => '8899',
'second' => '2299',
'third' => '1199',
default => p145_board_without_8888($t, $i),
},
'scope' => 'first',
],
];
foreach ($cases as $case) {
$player = p145_player(80_000_000);
$drawNo = p145_next_draw_no();
$draw = p145_draw($drawNo, random_int(1, 99_999));
$this->withHeader('Authorization', 'Bearer dev:'.$player->id)
->postJson('/api/v1/ticket/place', [
'draw_id' => $drawNo,
'currency_code' => 'NPR',
'client_trace_id' => 'module6-suffix-'.$case['play'].'-'.uniqid('', true),
'lines' => [
['number' => $case['number'], 'play_code' => $case['play'], 'amount' => 10_000],
],
])
->assertOk();
$item = TicketItem::query()->where('draw_id', $draw->id)->firstOrFail();
expect((int) $item->combination_count)->toBeIn([10, 100]);
$expectedWin = (int) floor(10_000 * OddsStandardScopes::PRESET_ODDS_BY_SCOPE[$case['scope']] / 10_000);
p145_publish_board($draw, $case['board']);
$draw->forceFill([
'status' => DrawStatus::Settling->value,
'current_result_version' => 1,
])->save();
expect(app(SettlementOrchestrator::class)->trySettleDraw($draw->fresh()), $case['play'])->toBeTrue();
p145_approve_and_payout($draw);
$item->refresh();
expect($item->status)->toBe('settled_win', $case['play'])
->and((int) $item->win_amount)->toBe($expectedWin, $case['play']);
}
});
test('§14.5 jackpot contributes on place and stays in pool when no first-prize burst', function (): void {
JackpotPool::query()->create([
'currency_code' => 'NPR',
@@ -371,6 +461,7 @@ test('§14.5 jackpot contributes on place and stays in pool when no first-prize
])->save();
expect(app(SettlementOrchestrator::class)->trySettleDraw($draw->fresh()))->toBeTrue();
p145_approve_and_payout($draw);
expect(JackpotPayoutLog::query()->count())->toBe(0);
$poolAfter = JackpotPool::query()->where('currency_code', 'NPR')->firstOrFail();
@@ -532,7 +623,7 @@ test('§14.5 straight roll box ibox mbox head tail odd even digit pos variants s
default => p145_board_without_8888($t, $i),
},
'scope' => 'second',
'comboMultiplier' => 10,
'comboMultiplier' => 1,
],
[
'play' => 'pos_3c',
@@ -542,7 +633,7 @@ test('§14.5 straight roll box ibox mbox head tail odd even digit pos variants s
default => p145_board_without_8888($t, $i),
},
'scope' => 'third',
'comboMultiplier' => 10,
'comboMultiplier' => 1,
],
[
'play' => 'pos_3abc',
@@ -554,7 +645,7 @@ test('§14.5 straight roll box ibox mbox head tail odd even digit pos variants s
default => p145_board_without_8888($t, $i),
},
'scope' => 'first',
'comboMultiplier' => 10,
'comboMultiplier' => 1,
],
[
'play' => 'pos_2b',
@@ -565,7 +656,7 @@ test('§14.5 straight roll box ibox mbox head tail odd even digit pos variants s
default => p145_board_without_8888($t, $i),
},
'scope' => 'second',
'comboMultiplier' => 100,
'comboMultiplier' => 1,
],
[
'play' => 'pos_2c',
@@ -577,7 +668,7 @@ test('§14.5 straight roll box ibox mbox head tail odd even digit pos variants s
default => p145_board_without_8888($t, $i),
},
'scope' => 'third',
'comboMultiplier' => 100,
'comboMultiplier' => 1,
],
[
'play' => 'pos_2abc',
@@ -589,7 +680,7 @@ test('§14.5 straight roll box ibox mbox head tail odd even digit pos variants s
default => p145_board_without_8888($t, $i),
},
'scope' => 'first',
'comboMultiplier' => 100,
'comboMultiplier' => 1,
],
];
@@ -631,6 +722,7 @@ test('§14.5 straight roll box ibox mbox head tail odd even digit pos variants s
])->save();
expect(app(SettlementOrchestrator::class)->trySettleDraw($draw->fresh()), $case['play'])->toBeTrue();
p145_approve_and_payout($draw);
$item->refresh();
expect($item->status)->toBe('settled_win', $case['play'])
@@ -672,6 +764,7 @@ test('§14.6 ticket detail shows settlement tier after win', function (): void {
])->save();
app(SettlementOrchestrator::class)->trySettleDraw($draw->fresh());
p145_approve_and_payout($draw);
$this->withHeader('Authorization', 'Bearer dev:'.$player->id)
->getJson('/api/v1/ticket/items/'.$ticketNo)

View File

@@ -110,6 +110,100 @@ test('ticket preview returns computed summary for open draw', function (): void
->assertJsonCount(2, 'data.lines');
});
test('module 6 box family expands combinations and computes amount semantics', function (): void {
$player = ticketPlayerWithWallet(500_000);
ticketOpenDraw();
$payload = [
'draw_id' => '20260511-001',
'currency_code' => 'NPR',
'client_trace_id' => 'trace-module6-box',
'lines' => [
['number' => '1234', 'play_code' => 'box', 'amount' => 10_000],
['number' => '1123', 'play_code' => 'box', 'amount' => 10_000],
['number' => '1122', 'play_code' => 'box', 'amount' => 10_000],
['number' => '1112', 'play_code' => 'box', 'amount' => 10_000],
['number' => '1111', 'play_code' => 'box', 'amount' => 10_000],
['number' => '1122', 'play_code' => 'ibox', 'amount' => 100],
['number' => '1234', 'play_code' => 'mbox', 'amount' => 10_001],
],
];
$resp = $this->withHeader('Authorization', 'Bearer dev:'.$player->id)
->postJson('/api/v1/ticket/preview', $payload)
->assertOk();
$lines = collect($resp->json('data.lines'))->keyBy('client_line_no');
expect($lines[1]['combination_count'])->toBe(24)
->and($lines[2]['combination_count'])->toBe(12)
->and($lines[3]['combination_count'])->toBe(6)
->and($lines[4]['combination_count'])->toBe(4)
->and($lines[5]['combination_count'])->toBe(1)
->and($lines[6]['combination_count'])->toBe(6)
->and($lines[6]['total_bet_amount'])->toBe(600)
->and($lines[7]['combination_count'])->toBe(24)
->and($lines[7]['total_bet_amount'])->toBe(9_984)
->and($lines[7]['actual_deduct_amount'])->toBe(9_984)
->and($lines[7]['rule_snapshot_json']['rounding_refund_amount'] ?? null)->toBe(17);
});
test('module 6 roll expands each R position and charges per expanded combination', function (): void {
$player = ticketPlayerWithWallet(500_000);
ticketOpenDraw();
$resp = $this->withHeader('Authorization', 'Bearer dev:'.$player->id)
->postJson('/api/v1/ticket/preview', [
'draw_id' => '20260511-001',
'currency_code' => 'NPR',
'client_trace_id' => 'trace-module6-roll',
'lines' => [
['number' => 'R234', 'play_code' => 'roll', 'amount' => 100],
['number' => 'RR34', 'play_code' => 'roll', 'amount' => 100],
],
])
->assertOk();
$lines = collect($resp->json('data.lines'))->keyBy('client_line_no');
expect($lines[1]['combination_count'])->toBe(10)
->and($lines[1]['total_bet_amount'])->toBe(1_000)
->and($lines[2]['combination_count'])->toBe(100)
->and($lines[2]['total_bet_amount'])->toBe(10_000);
});
test('module 6 reserved and phase two plays are not available for betting or public entry', function (): void {
$player = ticketPlayerWithWallet();
ticketOpenDraw();
$this->withHeader('Authorization', 'Bearer dev:'.$player->id)
->postJson('/api/v1/ticket/preview', [
'draw_id' => '20260511-001',
'currency_code' => 'NPR',
'client_trace_id' => 'trace-module6-half-box',
'lines' => [
['number' => '1234', 'play_code' => 'half_box', 'amount' => 10_000],
],
])
->assertStatus(400)
->assertJsonPath('code', ErrorCode::PlayModeClosed->value);
$this->withHeader('Authorization', 'Bearer dev:'.$player->id)
->postJson('/api/v1/ticket/preview', [
'draw_id' => '20260511-001',
'currency_code' => 'NPR',
'client_trace_id' => 'trace-module6-5d',
'lines' => [
['number' => '12345', 'play_code' => '5d', 'amount' => 10_000],
],
])
->assertStatus(400)
->assertJsonPath('code', ErrorCode::PlayModeClosed->value);
$plays = collect($this->getJson('/api/v1/play/effective?currency=NPR')->assertOk()->json('data.plays'));
expect($plays->firstWhere('play_code', 'half_box')['config']['is_enabled'])->toBeFalse()
->and($plays->contains('play_code', '5d'))->toBeFalse()
->and($plays->contains('play_code', '6d'))->toBeFalse();
});
test('ticket place deducts wallet and persists order items combinations and logs', function (): void {
$player = ticketPlayerWithWallet();
ticketOpenDraw();

View File

@@ -7,10 +7,16 @@ use App\Models\JackpotPool;
use App\Models\PlayerWallet;
use App\Models\DrawResultItem;
use App\Models\DrawResultBatch;
use App\Models\TicketOrder;
use App\Models\AdminUser;
use App\Models\SettlementBatch;
use App\Services\Draw\DrawPrizeLayout;
use App\Services\Settlement\SettlementOrchestrator;
use App\Services\Settlement\SettlementBatchWorkflowService;
use Database\Seeders\CurrencySeeder;
use Database\Seeders\PlayTypeSeeder;
use App\Lottery\DrawResultBatchStatus;
use App\Services\Draw\DrawPrizeLayout;
use Illuminate\Support\Facades\Hash;
use Database\Seeders\LotterySettingsSeeder;
use Database\Seeders\OperationalConfigV1Seeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
@@ -24,6 +30,79 @@ beforeEach(function (): void {
$this->seed(LotterySettingsSeeder::class);
});
function ticketItemsPlayer(): Player
{
$uniq = bin2hex(random_bytes(4));
$player = Player::query()->create([
'site_code' => 'test',
'site_player_id' => 'items-p-'.$uniq,
'username' => 'ti_'.$uniq,
'nickname' => null,
'default_currency' => 'NPR',
'status' => 0,
]);
PlayerWallet::query()->create([
'player_id' => $player->id,
'wallet_type' => 'lottery',
'currency_code' => 'NPR',
'balance' => 5_000_000,
'frozen_balance' => 0,
'status' => 0,
'version' => 0,
]);
return $player;
}
function ticketItemsPublishAndSettle(Draw $draw, string $firstNumber): void
{
$batch = DrawResultBatch::query()->create([
'draw_id' => $draw->id,
'result_version' => 1,
'source_type' => 'rng',
'rng_seed_hash' => 'items-'.(string) $draw->draw_no,
'raw_seed_encrypted' => null,
'status' => DrawResultBatchStatus::Published->value,
'created_by' => null,
'confirmed_by' => null,
'confirmed_at' => now(),
]);
foreach (DrawPrizeLayout::slots() as $slot) {
$num = $slot['prize_type'] === 'first' ? $firstNumber : '5678';
DrawResultItem::query()->create([
'draw_id' => $draw->id,
'result_batch_id' => $batch->id,
'prize_type' => $slot['prize_type'],
'prize_index' => $slot['prize_index'],
'number_4d' => $num,
'suffix_3d' => substr($num, -3),
'suffix_2d' => substr($num, -2),
'head_digit' => (int) substr($num, 0, 1),
'tail_digit' => (int) substr($num, 3, 1),
]);
}
$draw->forceFill([
'status' => DrawStatus::Settling->value,
'current_result_version' => 1,
])->save();
expect(app(SettlementOrchestrator::class)->trySettleDraw($draw->fresh()))->toBeTrue();
$admin = AdminUser::query()->create([
'username' => 'ticket_items_settle_'.bin2hex(random_bytes(3)),
'name' => 'Ticket Items Settle',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
grantSuperAdminRole($admin);
$settlementBatch = SettlementBatch::query()->where('draw_id', $draw->id)->firstOrFail();
app(SettlementBatchWorkflowService::class)->approve($settlementBatch, $admin);
app(SettlementBatchWorkflowService::class)->payout($settlementBatch->fresh());
}
test('jackpot summary is public', function (): void {
JackpotPool::query()->create([
'currency_code' => 'NPR',
@@ -44,24 +123,7 @@ test('jackpot summary is public', function (): void {
});
test('ticket items index returns placed ticket for player', function (): void {
$uniq = bin2hex(random_bytes(4));
$player = Player::query()->create([
'site_code' => 'test',
'site_player_id' => 'items-p-'.$uniq,
'username' => 'ti_'.$uniq,
'nickname' => null,
'default_currency' => 'NPR',
'status' => 0,
]);
PlayerWallet::query()->create([
'player_id' => $player->id,
'wallet_type' => 'lottery',
'currency_code' => 'NPR',
'balance' => 5_000_000,
'frozen_balance' => 0,
'status' => 0,
'version' => 0,
]);
$player = ticketItemsPlayer();
$draw = Draw::query()->create([
'draw_no' => '20260511-777',
@@ -117,6 +179,136 @@ test('ticket items index returns placed ticket for player', function (): void {
->assertJsonPath('data.total', 0);
});
test('ticket items index filters by status number and date range', function (): void {
$player = ticketItemsPlayer();
$draw1 = Draw::query()->create([
'draw_no' => '20260511-779',
'business_date' => '2026-05-11',
'sequence_no' => 779,
'status' => DrawStatus::Open->value,
'start_time' => now()->subMinutes(2),
'close_time' => now()->addMinutes(5),
'draw_time' => now()->addMinutes(6),
'cooling_end_time' => null,
'result_source' => null,
'current_result_version' => 0,
'settle_version' => 0,
'is_reopened' => false,
]);
$draw2 = Draw::query()->create([
'draw_no' => '20260512-780',
'business_date' => '2026-05-12',
'sequence_no' => 780,
'status' => DrawStatus::Open->value,
'start_time' => now()->subMinutes(2),
'close_time' => now()->addMinutes(5),
'draw_time' => now()->addMinutes(6),
'cooling_end_time' => null,
'result_source' => null,
'current_result_version' => 0,
'settle_version' => 0,
'is_reopened' => false,
]);
$this->withHeader('Authorization', 'Bearer dev:'.$player->id)
->postJson('/api/v1/ticket/place', [
'draw_id' => $draw1->draw_no,
'currency_code' => 'NPR',
'client_trace_id' => 'items-filter-1',
'lines' => [
['number' => '1234', 'play_code' => 'big', 'amount' => 10_000],
],
])
->assertOk();
$this->withHeader('Authorization', 'Bearer dev:'.$player->id)
->postJson('/api/v1/ticket/place', [
'draw_id' => $draw2->draw_no,
'currency_code' => 'NPR',
'client_trace_id' => 'items-filter-2',
'lines' => [
['number' => '4321', 'play_code' => 'big', 'amount' => 10_000],
],
])
->assertOk();
TicketOrder::query()->where('draw_id', $draw1->id)->update([
'created_at' => '2026-05-01 10:00:00',
'updated_at' => '2026-05-01 10:00:00',
]);
TicketOrder::query()->where('draw_id', $draw2->id)->update([
'created_at' => '2026-05-10 10:00:00',
'updated_at' => '2026-05-10 10:00:00',
]);
ticketItemsPublishAndSettle($draw2, '4321');
$this->withHeader('Authorization', 'Bearer dev:'.$player->id)
->getJson('/api/v1/ticket/items?status[]=settled_win')
->assertOk()
->assertJsonPath('data.total', 1)
->assertJsonPath('data.items.0.draw_no', '20260512-780');
$this->withHeader('Authorization', 'Bearer dev:'.$player->id)
->getJson('/api/v1/ticket/items?number=1234')
->assertOk()
->assertJsonPath('data.total', 1)
->assertJsonPath('data.items.0.original_number', '1234');
$this->withHeader('Authorization', 'Bearer dev:'.$player->id)
->getJson('/api/v1/ticket/items?start_date=2026-05-09&end_date=2026-05-11')
->assertOk()
->assertJsonPath('data.total', 1)
->assertJsonPath('data.items.0.draw_no', '20260512-780');
});
test('ticket item show returns match result and timeline', function (): void {
$player = ticketItemsPlayer();
$draw = Draw::query()->create([
'draw_no' => '20260513-781',
'business_date' => '2026-05-13',
'sequence_no' => 781,
'status' => DrawStatus::Open->value,
'start_time' => now()->subMinutes(2),
'close_time' => now()->addMinutes(5),
'draw_time' => now()->addMinutes(6),
'cooling_end_time' => null,
'result_source' => null,
'current_result_version' => 0,
'settle_version' => 0,
'is_reopened' => false,
]);
$this->withHeader('Authorization', 'Bearer dev:'.$player->id)
->postJson('/api/v1/ticket/place', [
'draw_id' => $draw->draw_no,
'currency_code' => 'NPR',
'client_trace_id' => 'items-detail-1',
'lines' => [
['number' => '1234', 'play_code' => 'big', 'amount' => 10_000],
],
])
->assertOk();
ticketItemsPublishAndSettle($draw, '1234');
$ticketNo = \App\Models\TicketItem::query()->where('draw_id', $draw->id)->value('ticket_no');
$this->withHeader('Authorization', 'Bearer dev:'.$player->id)
->getJson('/api/v1/ticket/items/'.$ticketNo)
->assertOk()
->assertJsonPath('data.match_result.matched', true)
->assertJsonPath('data.match_result.matched_prize_tier', 'first')
->assertJsonPath('data.timeline.0.code', 'placed')
->assertJsonPath('data.timeline.1.code', 'deducted')
->assertJsonPath('data.timeline.2.code', 'draw_published')
->assertJsonPath('data.timeline.3.code', 'settlement_started')
->assertJsonPath('data.timeline.4.code', 'settled');
});
test('my-match returns hit numbers when draw published', function (): void {
$uniq = bin2hex(random_bytes(4));
$player = Player::query()->create([