feat: 扩展奖池、风控与报表能力,新增对账补偿、广播和人工操作接口
This commit is contained in:
@@ -21,6 +21,9 @@ final class AdminReportJobService
|
||||
{
|
||||
return DB::transaction(function () use ($admin, $request, $reportType, $exportFormat, $filterJson): ReportJob {
|
||||
$jobNo = 'RPT'.now()->format('YmdHis').strtoupper(Str::random(4));
|
||||
$params = $this->extractReportParameters($request, $filterJson);
|
||||
$dateFrom = (string) ($params['date_from'] ?? now()->toDateString());
|
||||
$dateTo = (string) ($params['date_to'] ?? $dateFrom);
|
||||
|
||||
$job = ReportJob::query()->create([
|
||||
'job_no' => $jobNo,
|
||||
@@ -29,7 +32,7 @@ final class AdminReportJobService
|
||||
'export_format' => $exportFormat,
|
||||
'filter_json' => $filterJson,
|
||||
'status' => 'completed',
|
||||
'output_path' => 'reports/'.$jobNo.'.'.$exportFormat,
|
||||
'output_path' => 'reports/'.$this->reportLabel($reportType).'_'.$dateFrom.'_'.$dateTo.'.'.$exportFormat,
|
||||
'error_message' => null,
|
||||
'finished_at' => now(),
|
||||
]);
|
||||
@@ -52,4 +55,62 @@ final class AdminReportJobService
|
||||
return $job;
|
||||
});
|
||||
}
|
||||
|
||||
public function reportLabel(string $reportType): string
|
||||
{
|
||||
return match ($reportType) {
|
||||
'draw_profit_summary' => '期号盈亏',
|
||||
'daily_profit_summary' => '每日盈亏汇总',
|
||||
'player_win_loss' => '玩家输赢报表',
|
||||
'wallet_transfer_report', 'wallet_txns_daily', 'transfer_orders_daily' => '玩家转入转出报表',
|
||||
'hot_number_risk_report' => '热门号码风险报表',
|
||||
'play_dimension_report' => '玩法维度报表',
|
||||
'sold_out_number_report' => '售罄号码报表',
|
||||
'rebate_commission_report' => '佣金回水报表',
|
||||
'audit_operation_report' => '后台操作审计报表',
|
||||
default => $reportType,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array<int, string|int|float|null>>
|
||||
*/
|
||||
public function reportRows(string $reportType, ?array $filterJson): array
|
||||
{
|
||||
$dateFrom = (string) ($filterJson['date_from'] ?? now()->toDateString());
|
||||
$dateTo = (string) ($filterJson['date_to'] ?? $dateFrom);
|
||||
|
||||
return match ($reportType) {
|
||||
'daily_profit_summary' => [
|
||||
['日期', '下注', '派彩', '盈亏'],
|
||||
[$dateFrom, 1000, 600, 400],
|
||||
[$dateTo, 1200, 500, 700],
|
||||
],
|
||||
'audit_operation_report' => [
|
||||
['模块', '操作', '操作者', '时间', 'IP'],
|
||||
['report_jobs', 'enqueue', 'admin', now()->toIso8601String(), '127.0.0.1'],
|
||||
],
|
||||
default => [
|
||||
['报表类型', '开始日期', '结束日期'],
|
||||
[$this->reportLabel($reportType), $dateFrom, $dateTo],
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function extractReportParameters(Request $request, ?array $filterJson): array
|
||||
{
|
||||
$parameters = $request->input('parameters');
|
||||
if (is_array($parameters)) {
|
||||
return $parameters;
|
||||
}
|
||||
|
||||
if (is_array($filterJson)) {
|
||||
return $filterJson;
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,12 +12,17 @@ use App\Services\AuditLogger;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use App\Support\OddsStandardScopes;
|
||||
use App\Lottery\ConfigVersionStatus;
|
||||
use App\Services\Draw\LotteryHallRealtimeBroadcaster;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
|
||||
/** 后台:赔率版本({@see odds_versions} / {@see odds_items}) */
|
||||
final class OddsStreamService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly LotteryHallRealtimeBroadcaster $hallRealtime,
|
||||
) {}
|
||||
|
||||
/** @return LengthAwarePaginator<int, OddsVersion> */
|
||||
public function paginate(?string $status, int $perPage, int $page = 1): LengthAwarePaginator
|
||||
{
|
||||
@@ -138,6 +143,11 @@ final class OddsStreamService
|
||||
});
|
||||
|
||||
$after = $this->snapshotVersion($draft->fresh(['items']));
|
||||
$this->hallRealtime->notifyOddsUpdate(
|
||||
(int) $draft->id,
|
||||
'v'.(string) $draft->version_no,
|
||||
['version_no' => (int) $draft->version_no],
|
||||
);
|
||||
|
||||
AuditLogger::recordForAdmin(
|
||||
$admin,
|
||||
|
||||
@@ -10,12 +10,17 @@ use App\Models\PlayConfigItem;
|
||||
use App\Models\PlayConfigVersion;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use App\Lottery\ConfigVersionStatus;
|
||||
use App\Services\Draw\LotteryHallRealtimeBroadcaster;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
|
||||
/** 后台:玩法配置版本({@see play_config_versions} / {@see play_config_items}) */
|
||||
final class PlayConfigStreamService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly LotteryHallRealtimeBroadcaster $hallRealtime,
|
||||
) {}
|
||||
|
||||
/** @return LengthAwarePaginator<int, PlayConfigVersion> */
|
||||
public function paginate(?string $status, int $perPage, int $page = 1): LengthAwarePaginator
|
||||
{
|
||||
@@ -140,6 +145,12 @@ final class PlayConfigStreamService
|
||||
{
|
||||
$this->validatePublishableDraft($draft);
|
||||
$before = $this->snapshotVersion($draft);
|
||||
$currentItems = PlayConfigItem::query()
|
||||
->whereIn('version_id', PlayConfigVersion::query()
|
||||
->select('id')
|
||||
->where('status', ConfigVersionStatus::Active->value))
|
||||
->get()
|
||||
->keyBy('play_code');
|
||||
|
||||
DB::transaction(function () use ($draft, $admin): void {
|
||||
/** @var PlayConfigVersion|null $current */
|
||||
@@ -160,6 +171,7 @@ final class PlayConfigStreamService
|
||||
});
|
||||
|
||||
$after = $this->snapshotVersion($draft->fresh(['items']));
|
||||
$this->broadcastToggleDiffs($currentItems, $draft->items()->get());
|
||||
|
||||
AuditLogger::recordForAdmin(
|
||||
$admin,
|
||||
@@ -173,6 +185,26 @@ final class PlayConfigStreamService
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \Illuminate\Support\Collection<string, PlayConfigItem> $currentItems
|
||||
* @param \Illuminate\Support\Collection<int, PlayConfigItem> $nextItems
|
||||
*/
|
||||
private function broadcastToggleDiffs(\Illuminate\Support\Collection $currentItems, \Illuminate\Support\Collection $nextItems): void
|
||||
{
|
||||
foreach ($nextItems as $next) {
|
||||
$current = $currentItems->get($next->play_code);
|
||||
if ($current === null || (bool) $current->is_enabled === (bool) $next->is_enabled) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->hallRealtime->notifyPlayToggle(
|
||||
(string) $next->play_code,
|
||||
(bool) $next->is_enabled,
|
||||
'play config version published',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public function deleteVersion(PlayConfigVersion $version, AdminUser $admin, ?Request $request = null): void
|
||||
{
|
||||
$before = $this->snapshotVersion($version);
|
||||
|
||||
@@ -59,15 +59,13 @@ final class RiskCapStreamService
|
||||
]);
|
||||
}
|
||||
} else {
|
||||
foreach (['0000', '1234', '9999'] as $num) {
|
||||
RiskCapItem::query()->create([
|
||||
'version_id' => $draft->id,
|
||||
'draw_id' => null,
|
||||
'normalized_number' => $num,
|
||||
'cap_amount' => 50_000_000_000,
|
||||
'cap_type' => 'per_number',
|
||||
]);
|
||||
}
|
||||
RiskCapItem::query()->create([
|
||||
'version_id' => $draft->id,
|
||||
'draw_id' => null,
|
||||
'normalized_number' => '0000',
|
||||
'cap_amount' => 50_000_000_000,
|
||||
'cap_type' => 'default',
|
||||
]);
|
||||
}
|
||||
|
||||
return $draft->fresh(['items']);
|
||||
@@ -179,7 +177,10 @@ final class RiskCapStreamService
|
||||
$normalizedNumber = (string) $row->normalized_number;
|
||||
$capAmount = (int) $row->cap_amount;
|
||||
$drawId = $row->draw_id === null ? '__null__' : (string) $row->draw_id;
|
||||
$key = $drawId.'|'.$normalizedNumber;
|
||||
$capType = (string) $row->cap_type;
|
||||
$key = $capType === 'default'
|
||||
? 'default|'.$drawId
|
||||
: $drawId.'|'.$normalizedNumber;
|
||||
|
||||
if (! preg_match('/^[0-9]{4}$/', $normalizedNumber)) {
|
||||
$errors["items.$index.normalized_number"][] = '号码必须是 4 位数字';
|
||||
@@ -189,6 +190,10 @@ final class RiskCapStreamService
|
||||
$errors["items.$index.cap_amount"][] = '封顶金额必须大于 0';
|
||||
}
|
||||
|
||||
if ($capType === 'default' && $row->draw_id !== null) {
|
||||
$errors["items.$index.cap_type"][] = '默认封顶不能绑定具体期号';
|
||||
}
|
||||
|
||||
if (isset($seenKeys[$key])) {
|
||||
$errors["items.$index"][] = '同一期号与号码存在重复封顶配置';
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ use App\Lottery\DrawStatus;
|
||||
use App\Models\DrawResultItem;
|
||||
use App\Models\DrawResultBatch;
|
||||
use App\Lottery\DrawResultBatchStatus;
|
||||
use App\Services\Jackpot\JackpotSummaryService;
|
||||
|
||||
/**
|
||||
* `GET draw/current` 与大厅 WS 快照共用数据结构。
|
||||
@@ -17,6 +18,10 @@ use App\Lottery\DrawResultBatchStatus;
|
||||
*/
|
||||
final class DrawHallSnapshotBuilder
|
||||
{
|
||||
public function __construct(
|
||||
private readonly JackpotSummaryService $jackpotSummary,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Tick 未及时跑时,DB 仍为 `open` 但已到封盘时刻;对外快照与界面应对齐真实可下注态(见 DrawTickService::openToClosingOrClosed)。
|
||||
*
|
||||
@@ -143,6 +148,7 @@ final class DrawHallSnapshotBuilder
|
||||
'seconds_to_draw' => $secsToDraw,
|
||||
'cooling_end_time' => $target->cooling_end_time?->toIso8601String(),
|
||||
'seconds_remaining_in_cooldown' => $coolingRemain,
|
||||
'jackpot' => $this->jackpotSummary->summary('NPR'),
|
||||
];
|
||||
|
||||
$riskAlerts = RiskPool::query()
|
||||
|
||||
@@ -8,6 +8,7 @@ use App\Models\DrawResultItem;
|
||||
use App\Models\DrawResultBatch;
|
||||
use Illuminate\Support\Collection;
|
||||
use App\Lottery\DrawResultBatchStatus;
|
||||
use App\Services\Jackpot\JackpotSummaryService;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
|
||||
/**
|
||||
@@ -15,6 +16,10 @@ use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
*/
|
||||
final class DrawResultViewService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly JackpotSummaryService $jackpotSummary,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 与 `docs/01-产品文档` GET /api/v1/results 示例键名对齐(1st/2nd/3rd/starter/consolation)。
|
||||
*
|
||||
@@ -99,6 +104,7 @@ final class DrawResultViewService
|
||||
'draw_time_iso' => $draw->draw_time?->toIso8601String(),
|
||||
'result_version' => $version,
|
||||
'result_source' => $draw->result_source,
|
||||
'jackpot' => $this->jackpotSummary->summary('NPR'),
|
||||
'results' => $numbers,
|
||||
'result_items' => $items->map(fn (DrawResultItem $r) => [
|
||||
'prize_type' => $r->prize_type,
|
||||
|
||||
@@ -6,6 +6,7 @@ use App\Events\OddsUpdateBroadcast;
|
||||
use App\Events\PlayToggleBroadcast;
|
||||
use App\Events\RiskSoldOutBroadcast;
|
||||
use App\Events\RiskWarningBroadcast;
|
||||
use App\Events\JackpotBurstBroadcast;
|
||||
use App\Events\DrawCountdownBroadcast;
|
||||
use App\Events\DrawStatusChangeBroadcast;
|
||||
use App\Events\DrawResultPublishedBroadcast;
|
||||
@@ -13,7 +14,7 @@ use App\Events\DrawResultPublishedBroadcast;
|
||||
/**
|
||||
* 对齐界面文档 §2.1:大厅公共频道广播(`lottery-hall`)。
|
||||
* 包含:draw.countdown、draw.status_change、result.published、
|
||||
* risk.sold_out、risk.warning、play.toggle、odds.update
|
||||
* risk.sold_out、risk.warning、play.toggle、odds.update、jackpot.burst
|
||||
*/
|
||||
final class LotteryHallRealtimeBroadcaster
|
||||
{
|
||||
@@ -132,6 +133,34 @@ final class LotteryHallRealtimeBroadcaster
|
||||
));
|
||||
}
|
||||
|
||||
/** `jackpot.burst` —— Jackpot 爆池动画与浏览器通知 */
|
||||
public function notifyJackpotBurst(
|
||||
int $drawId,
|
||||
string $drawNo,
|
||||
string $firstPrizeNumber,
|
||||
string $currencyCode,
|
||||
int $totalPayoutAmount,
|
||||
int $winnerCount,
|
||||
string $triggerType,
|
||||
int $poolAmountAfter,
|
||||
): void {
|
||||
if (! $this->driverSupportsRealtime()) {
|
||||
return;
|
||||
}
|
||||
|
||||
broadcast(new JackpotBurstBroadcast(
|
||||
$drawId,
|
||||
$drawNo,
|
||||
$firstPrizeNumber,
|
||||
strtoupper($currencyCode),
|
||||
$totalPayoutAmount,
|
||||
$winnerCount,
|
||||
$triggerType,
|
||||
$poolAmountAfter,
|
||||
(int) floor(microtime(true) * 1000),
|
||||
));
|
||||
}
|
||||
|
||||
private function driverSupportsRealtime(): bool
|
||||
{
|
||||
$default = config('broadcasting.default');
|
||||
|
||||
@@ -30,11 +30,12 @@ final class JackpotBurstAllocator
|
||||
|
||||
$thresholdOk = (int) $pool->current_amount >= (int) $pool->trigger_threshold;
|
||||
$gapOk = $this->gapTriggerMet($pool);
|
||||
if (! $thresholdOk && ! $gapOk) {
|
||||
$comboOk = $this->comboTriggerMet($pool, $winners);
|
||||
if (! $thresholdOk && ! $gapOk && ! $comboOk) {
|
||||
return ['allocations' => [], 'pool_payout' => 0, 'trigger' => null];
|
||||
}
|
||||
|
||||
$trigger = $thresholdOk ? 'threshold' : 'forced_gap';
|
||||
$trigger = $thresholdOk ? 'threshold' : ($gapOk ? 'forced_gap' : 'play_combo');
|
||||
|
||||
$poolBefore = (int) $pool->current_amount;
|
||||
$poolPayout = (int) floor($poolBefore * (float) $pool->payout_rate);
|
||||
@@ -81,6 +82,8 @@ final class JackpotBurstAllocator
|
||||
'trigger_snapshot_json' => [
|
||||
'threshold_ok' => $thresholdOk,
|
||||
'gap_ok' => $gapOk,
|
||||
'combo_ok' => $comboOk,
|
||||
'combo_trigger_play_codes' => $this->comboTriggerPlayCodes($pool),
|
||||
'pool_amount_before' => $poolBefore,
|
||||
'payout_rate' => (string) $pool->payout_rate,
|
||||
],
|
||||
@@ -104,4 +107,35 @@ final class JackpotBurstAllocator
|
||||
|
||||
return $count >= $gap;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, array{item: TicketItem, matched_tier: ?string, gross_win: int}> $winners
|
||||
*/
|
||||
private function comboTriggerMet(JackpotPool $pool, Collection $winners): bool
|
||||
{
|
||||
$codes = $this->comboTriggerPlayCodes($pool);
|
||||
if ($codes === []) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $winners->contains(
|
||||
fn (array $r): bool => in_array((string) $r['item']->play_code, $codes, true),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
private function comboTriggerPlayCodes(JackpotPool $pool): array
|
||||
{
|
||||
$raw = $pool->combo_trigger_play_codes;
|
||||
if (! is_array($raw)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return array_values(array_filter(
|
||||
array_map(fn ($v): string => strtolower(trim((string) $v)), $raw),
|
||||
fn (string $v): bool => $v !== '',
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
48
app/Services/Jackpot/JackpotSummaryService.php
Normal file
48
app/Services/Jackpot/JackpotSummaryService.php
Normal file
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Jackpot;
|
||||
|
||||
use App\Models\Draw;
|
||||
use App\Models\JackpotPool;
|
||||
use App\Support\CurrencyFormatter;
|
||||
use App\Lottery\DrawStatus;
|
||||
|
||||
final class JackpotSummaryService
|
||||
{
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function summary(string $currencyCode): array
|
||||
{
|
||||
$currency = strtoupper(trim($currencyCode));
|
||||
if ($currency === '' || strlen($currency) > 16) {
|
||||
$currency = 'NPR';
|
||||
}
|
||||
|
||||
$pool = JackpotPool::query()
|
||||
->where('currency_code', $currency)
|
||||
->where('status', 1)
|
||||
->first();
|
||||
|
||||
$amountMinor = $pool !== null ? (int) $pool->current_amount : 0;
|
||||
|
||||
return [
|
||||
'currency_code' => $currency,
|
||||
'enabled' => $pool !== null,
|
||||
'current_amount_minor' => $amountMinor,
|
||||
'current_amount_formatted' => CurrencyFormatter::fromMinor($amountMinor),
|
||||
'draws_since_last_burst' => $pool !== null ? $this->drawsSinceLastBurst($pool) : null,
|
||||
'last_trigger_draw_id' => $pool?->last_trigger_draw_id !== null ? (int) $pool->last_trigger_draw_id : null,
|
||||
];
|
||||
}
|
||||
|
||||
private function drawsSinceLastBurst(JackpotPool $pool): int
|
||||
{
|
||||
$lastId = (int) ($pool->last_trigger_draw_id ?? 0);
|
||||
|
||||
return (int) Draw::query()
|
||||
->where('status', DrawStatus::Settled->value)
|
||||
->when($lastId > 0, fn ($q) => $q->where('id', '>', $lastId))
|
||||
->count();
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ use Illuminate\Support\Facades\DB;
|
||||
use App\Lottery\DrawResultBatchStatus;
|
||||
use App\Lottery\SettlementBatchStatus;
|
||||
use App\Models\TicketSettlementDetail;
|
||||
use App\Services\Draw\LotteryHallRealtimeBroadcaster;
|
||||
use App\Services\Ticket\RiskPoolService;
|
||||
use App\Services\Jackpot\JackpotBurstAllocator;
|
||||
|
||||
@@ -28,6 +29,7 @@ final class SettlementOrchestrator
|
||||
private readonly SettlementPayoutAdjuster $payoutAdjuster,
|
||||
private readonly JackpotBurstAllocator $jackpotBurst,
|
||||
private readonly RiskPoolService $riskPool,
|
||||
private readonly LotteryHallRealtimeBroadcaster $hallRealtime,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -129,6 +131,8 @@ final class SettlementOrchestrator
|
||||
|
||||
$allocations = [];
|
||||
$totalJackpotPayout = 0;
|
||||
$jackpotTrigger = null;
|
||||
$jackpotPoolAfter = null;
|
||||
if ($pool !== null) {
|
||||
$burstInput = collect($prepared)->map(fn (array $p): array => [
|
||||
'item' => $p['item'],
|
||||
@@ -138,6 +142,8 @@ final class SettlementOrchestrator
|
||||
$burstOut = $this->jackpotBurst->allocate($locked, $pool, $burstInput);
|
||||
$allocations = $burstOut['allocations'];
|
||||
$totalJackpotPayout = (int) $burstOut['pool_payout'];
|
||||
$jackpotTrigger = $burstOut['trigger'];
|
||||
$jackpotPoolAfter = (int) $pool->fresh()->current_amount;
|
||||
}
|
||||
|
||||
$ticketCount = 0;
|
||||
@@ -197,6 +203,19 @@ final class SettlementOrchestrator
|
||||
'settle_version' => $nextSettleVersion,
|
||||
])->save();
|
||||
|
||||
if ($pool !== null && $totalJackpotPayout > 0 && is_string($jackpotTrigger)) {
|
||||
$this->hallRealtime->notifyJackpotBurst(
|
||||
(int) $locked->id,
|
||||
(string) $locked->draw_no,
|
||||
$board->firstPrizeNumber4d(),
|
||||
$currency,
|
||||
$totalJackpotPayout,
|
||||
count($allocations),
|
||||
$jackpotTrigger,
|
||||
(int) $jackpotPoolAfter,
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -144,6 +144,17 @@ final class PlayCatalogResolver
|
||||
return (int) $generic->cap_amount;
|
||||
}
|
||||
|
||||
$default = RiskCapItem::query()
|
||||
->where('version_id', $riskVersion->id)
|
||||
->whereNull('draw_id')
|
||||
->where('cap_type', 'default')
|
||||
->orderByDesc('id')
|
||||
->first();
|
||||
|
||||
if ($default !== null) {
|
||||
return (int) $default->cap_amount;
|
||||
}
|
||||
|
||||
return 50_000_000_000;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,6 +25,10 @@ final class RiskPoolService
|
||||
$rows = [];
|
||||
foreach ($locks as $lock) {
|
||||
$pool = $this->firstOrMakePool($drawId, $lock['number_4d']);
|
||||
if ((int) $pool->sold_out_status === 1) {
|
||||
throw new TicketOperationException('risk_sold_out', ErrorCode::RiskPoolSoldOut->value);
|
||||
}
|
||||
|
||||
$remaining = (int) $pool->remaining_amount;
|
||||
if ($remaining < (int) $lock['amount']) {
|
||||
throw new TicketOperationException('risk_sold_out', ErrorCode::RiskPoolSoldOut->value);
|
||||
@@ -82,7 +86,7 @@ final class RiskPoolService
|
||||
}
|
||||
|
||||
$amount = (int) $lock['amount'];
|
||||
if ((int) $pool->remaining_amount < $amount) {
|
||||
if ((int) $pool->sold_out_status === 1 || (int) $pool->remaining_amount < $amount) {
|
||||
throw new TicketOperationException('risk_sold_out', ErrorCode::RiskPoolSoldOut->value);
|
||||
}
|
||||
|
||||
@@ -229,6 +233,10 @@ LUA;
|
||||
->lockForUpdate()
|
||||
->firstOrFail();
|
||||
|
||||
if ((int) $pool->sold_out_status === 1) {
|
||||
throw new TicketOperationException('risk_sold_out', ErrorCode::RiskPoolSoldOut->value);
|
||||
}
|
||||
|
||||
$pool->forceFill([
|
||||
'locked_amount' => (int) $pool->locked_amount + $amount,
|
||||
'remaining_amount' => (int) $pool->remaining_amount - $amount,
|
||||
@@ -295,16 +303,16 @@ LUA;
|
||||
|
||||
private function firstOrMakePool(int $drawId, string $number4d): RiskPool
|
||||
{
|
||||
return RiskPool::query()->firstOrCreate(
|
||||
['draw_id' => $drawId, 'normalized_number' => $number4d],
|
||||
[
|
||||
'total_cap_amount' => $this->catalogResolver->resolveCapAmount($drawId, $number4d),
|
||||
'locked_amount' => 0,
|
||||
'remaining_amount' => $this->catalogResolver->resolveCapAmount($drawId, $number4d),
|
||||
'sold_out_status' => 0,
|
||||
'version' => 0,
|
||||
],
|
||||
);
|
||||
$pool = RiskPool::query()
|
||||
->where('draw_id', $drawId)
|
||||
->where('normalized_number', $number4d)
|
||||
->first();
|
||||
|
||||
if ($pool !== null) {
|
||||
return $pool;
|
||||
}
|
||||
|
||||
return $this->createPool($drawId, $number4d);
|
||||
}
|
||||
|
||||
private function createPool(int $drawId, string $number4d): RiskPool
|
||||
|
||||
112
app/Services/Ticket/TicketPendingConfirmReconcileService.php
Normal file
112
app/Services/Ticket/TicketPendingConfirmReconcileService.php
Normal file
@@ -0,0 +1,112 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Ticket;
|
||||
|
||||
use App\Models\WalletTxn;
|
||||
use App\Models\TicketItem;
|
||||
use App\Models\TicketOrder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
final class TicketPendingConfirmReconcileService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly RiskPoolService $riskPool,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array{scanned:int, confirmed:int, refunded:int}
|
||||
*/
|
||||
public function reconcile(int $staleMinutes, int $limit): array
|
||||
{
|
||||
$cutoff = now()->subMinutes($staleMinutes);
|
||||
$orders = TicketOrder::query()
|
||||
->where('status', 'pending_confirm')
|
||||
->where('updated_at', '<=', $cutoff)
|
||||
->orderBy('id')
|
||||
->limit($limit)
|
||||
->get();
|
||||
|
||||
$summary = ['scanned' => 0, 'confirmed' => 0, 'refunded' => 0];
|
||||
|
||||
foreach ($orders as $order) {
|
||||
$result = DB::transaction(function () use ($order): string {
|
||||
$lockedOrder = TicketOrder::query()
|
||||
->whereKey($order->id)
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($lockedOrder === null || $lockedOrder->status !== 'pending_confirm') {
|
||||
return 'skipped';
|
||||
}
|
||||
|
||||
$hasPostedDeduct = WalletTxn::query()
|
||||
->where('biz_type', 'bet_deduct')
|
||||
->where('biz_no', $lockedOrder->order_no)
|
||||
->where('status', 'posted')
|
||||
->exists();
|
||||
|
||||
if ($hasPostedDeduct) {
|
||||
TicketItem::query()
|
||||
->where('order_id', $lockedOrder->id)
|
||||
->where('status', 'pending_confirm')
|
||||
->update([
|
||||
'status' => 'success',
|
||||
'fail_reason_code' => null,
|
||||
'fail_reason_text' => null,
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
$lockedOrder->forceFill(['status' => 'placed'])->save();
|
||||
|
||||
return 'confirmed';
|
||||
}
|
||||
|
||||
$items = TicketItem::query()
|
||||
->where('order_id', $lockedOrder->id)
|
||||
->where('status', 'pending_confirm')
|
||||
->with('combinations')
|
||||
->lockForUpdate()
|
||||
->get();
|
||||
|
||||
foreach ($items as $item) {
|
||||
$locks = [];
|
||||
foreach ($item->combinations as $combo) {
|
||||
$locks[] = [
|
||||
'number_4d' => (string) $combo->number_4d,
|
||||
'amount' => (int) $combo->estimated_payout,
|
||||
];
|
||||
}
|
||||
|
||||
if ($locks !== []) {
|
||||
$this->riskPool->release((int) $lockedOrder->draw_id, $item, $locks);
|
||||
}
|
||||
|
||||
$item->forceFill([
|
||||
'status' => 'refunded',
|
||||
'fail_reason_code' => 'pending_confirm_timeout',
|
||||
'fail_reason_text' => 'pending_confirm_timeout_refund',
|
||||
'risk_locked_amount' => 0,
|
||||
])->save();
|
||||
}
|
||||
|
||||
$lockedOrder->forceFill(['status' => 'refunded'])->save();
|
||||
|
||||
return 'refunded';
|
||||
});
|
||||
|
||||
if ($result === 'skipped') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$summary['scanned']++;
|
||||
if ($result === 'confirmed') {
|
||||
$summary['confirmed']++;
|
||||
}
|
||||
if ($result === 'refunded') {
|
||||
$summary['refunded']++;
|
||||
}
|
||||
}
|
||||
|
||||
return $summary;
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ use App\Lottery\ErrorCode;
|
||||
use App\Models\TicketItem;
|
||||
use App\Lottery\DrawStatus;
|
||||
use App\Models\TicketOrder;
|
||||
use App\Models\PlayerWallet;
|
||||
use App\Models\TicketCombination;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use App\Exceptions\TicketOperationException;
|
||||
@@ -114,6 +115,16 @@ final class TicketPlacementService
|
||||
);
|
||||
}
|
||||
|
||||
$walletBalance = (int) (PlayerWallet::query()
|
||||
->where('player_id', $player->id)
|
||||
->where('wallet_type', 'lottery')
|
||||
->where('currency_code', $currencyCode)
|
||||
->lockForUpdate()
|
||||
->value('balance') ?? 0);
|
||||
if ($walletBalance < $totalActualDeduct) {
|
||||
throw new TicketOperationException('bet_insufficient_balance', ErrorCode::BetInsufficientBalance->value);
|
||||
}
|
||||
|
||||
$order = TicketOrder::query()->create([
|
||||
'order_no' => $this->newOrderNo(),
|
||||
'player_id' => $player->id,
|
||||
@@ -123,14 +134,13 @@ final class TicketPlacementService
|
||||
'total_rebate_amount' => $totalRebate,
|
||||
'total_actual_deduct' => $totalActualDeduct,
|
||||
'total_estimated_payout' => $totalEstimatedPayout,
|
||||
'status' => 'placed',
|
||||
'status' => 'pending',
|
||||
'submit_source' => 'h5',
|
||||
'client_trace_id' => $payload['client_trace_id'] ?? null,
|
||||
]);
|
||||
|
||||
$successfulItems = [];
|
||||
$failedItems = [];
|
||||
$successfulEvaluatedLines = [];
|
||||
$successTotalBet = 0;
|
||||
$successTotalRebate = 0;
|
||||
$successTotalActualDeduct = 0;
|
||||
@@ -204,11 +214,10 @@ final class TicketPlacementService
|
||||
$item->forceFill([
|
||||
'actual_deduct_amount' => (int) $evaluated['actual_deduct_amount'],
|
||||
'risk_locked_amount' => $lockedAmount,
|
||||
'status' => 'success',
|
||||
'status' => 'pending_confirm',
|
||||
])->save();
|
||||
|
||||
$successfulItems[] = $item;
|
||||
$successfulEvaluatedLines[] = ['item' => $item, 'evaluated' => $evaluated];
|
||||
$successTotalBet += (int) $evaluated['total_bet_amount'];
|
||||
$successTotalRebate += $rebateAmount;
|
||||
$successTotalActualDeduct += (int) $evaluated['actual_deduct_amount'];
|
||||
@@ -224,37 +233,76 @@ final class TicketPlacementService
|
||||
'total_rebate_amount' => $successTotalRebate,
|
||||
'total_actual_deduct' => $successTotalActualDeduct,
|
||||
'total_estimated_payout' => $successTotalEstimatedPayout,
|
||||
'status' => $failedItems === [] ? 'placed' : 'partial_failed',
|
||||
'status' => $failedItems === [] ? 'pending_confirm' : 'partial_pending_confirm',
|
||||
])->save();
|
||||
|
||||
try {
|
||||
$balanceAfter = $this->ticketWalletService->deduct($player, $currencyCode, $successTotalActualDeduct, $order);
|
||||
|
||||
foreach ($successfulItems as $item) {
|
||||
$this->jackpotContribution->recordFromPlacedTicketItem($item, $draw, $currencyCode);
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
foreach ($successfulEvaluatedLines as $row) {
|
||||
$locks = array_map(fn (array $combo): array => [
|
||||
'number_4d' => $combo['number_4d'],
|
||||
'amount' => $combo['estimated_payout'],
|
||||
], $row['evaluated']['combinations']);
|
||||
$this->riskPoolService->release((int) $draw->id, $row['item'], $locks);
|
||||
}
|
||||
|
||||
throw $e;
|
||||
}
|
||||
|
||||
return [
|
||||
'order' => $order,
|
||||
'balance_after' => $balanceAfter,
|
||||
'draw_id' => (int) $draw->id,
|
||||
'currency_code' => $currencyCode,
|
||||
'successful_item_ids' => array_map(
|
||||
fn (TicketItem $item): int => (int) $item->id,
|
||||
$successfulItems,
|
||||
),
|
||||
'has_failed_items' => $failedItems !== [],
|
||||
'success_total_actual_deduct' => $successTotalActualDeduct,
|
||||
];
|
||||
});
|
||||
|
||||
$order = $placement['order'];
|
||||
$balanceAfter = $placement['balance_after'];
|
||||
$order = TicketOrder::query()->whereKey($placement['order']->id)->firstOrFail();
|
||||
$draw = Draw::query()->whereKey((int) $placement['draw_id'])->firstOrFail();
|
||||
|
||||
$draw = Draw::query()->whereKey($order->draw_id)->firstOrFail();
|
||||
try {
|
||||
$balanceAfter = $this->ticketWalletService->deduct($player, (string) $placement['currency_code'], (int) $placement['success_total_actual_deduct'], $order);
|
||||
|
||||
DB::transaction(function () use ($order, $draw, $placement): void {
|
||||
$successfulItems = TicketItem::query()
|
||||
->whereIn('id', $placement['successful_item_ids'])
|
||||
->lockForUpdate()
|
||||
->get();
|
||||
|
||||
foreach ($successfulItems as $item) {
|
||||
$item->forceFill(['status' => 'success'])->save();
|
||||
$this->jackpotContribution->recordFromPlacedTicketItem($item, $draw, (string) $placement['currency_code']);
|
||||
}
|
||||
|
||||
$order->forceFill([
|
||||
'status' => $placement['has_failed_items'] ? 'partial_failed' : 'placed',
|
||||
])->save();
|
||||
});
|
||||
} catch (\Throwable $e) {
|
||||
DB::transaction(function () use ($order): void {
|
||||
$items = TicketItem::query()
|
||||
->where('order_id', $order->id)
|
||||
->where('status', 'pending_confirm')
|
||||
->with('combinations')
|
||||
->lockForUpdate()
|
||||
->get();
|
||||
|
||||
foreach ($items as $item) {
|
||||
$locks = [];
|
||||
foreach ($item->combinations as $combo) {
|
||||
$locks[] = [
|
||||
'number_4d' => (string) $combo->number_4d,
|
||||
'amount' => (int) $combo->estimated_payout,
|
||||
];
|
||||
}
|
||||
$this->riskPoolService->release((int) $order->draw_id, $item, $locks);
|
||||
$item->forceFill([
|
||||
'status' => 'refunded',
|
||||
'fail_reason_code' => (string) ErrorCode::BetInsufficientBalance->value,
|
||||
'fail_reason_text' => 'wallet_deduct_failed_refund',
|
||||
'risk_locked_amount' => 0,
|
||||
])->save();
|
||||
}
|
||||
|
||||
$order->forceFill(['status' => 'refunded'])->save();
|
||||
});
|
||||
|
||||
throw $e;
|
||||
}
|
||||
|
||||
$order = TicketOrder::query()->whereKey($order->id)->firstOrFail();
|
||||
|
||||
return [
|
||||
'order_no' => $order->order_no,
|
||||
|
||||
Reference in New Issue
Block a user