refactor: 更新权限管理与请求验证逻辑
- 在多个控制器中将权限检查从 hasAdminPermission 更新为 hasPermissionCode,以增强权限管理的灵活性。 - 引入 AdminScopePolicy,优化基于代理节点的权限和数据过滤逻辑,确保管理员能够更精确地控制访问权限。 - 在请求验证中添加 agent_node_id 字段,确保 API 接口支持代理节点的相关操作。 - 更新 AdminUser 模型,新增 hasPermissionCode 方法,以支持更细粒度的权限检查。 - 优化审计日志记录逻辑,确保在处理请求时能够准确记录管理员的操作。
This commit is contained in:
@@ -3,6 +3,7 @@
|
||||
namespace App\Services\Admin;
|
||||
|
||||
use App\Models\AdminUser;
|
||||
use App\Support\AdminScopeContextResolver;
|
||||
|
||||
/**
|
||||
* 仪表盘可筛选分析数据:区间汇总、日趋势、玩法拆解。
|
||||
@@ -30,6 +31,12 @@ final class AdminDashboardAnalyticsBuilder
|
||||
return null;
|
||||
}
|
||||
|
||||
$scope = AdminScopeContextResolver::fromValues(
|
||||
$admin,
|
||||
requestedSiteCode: isset($filters['site_code']) ? (string) $filters['site_code'] : null,
|
||||
requestedAgentNodeId: isset($filters['agent_node_id']) ? (int) $filters['agent_node_id'] : null,
|
||||
);
|
||||
|
||||
$period = (string) ($filters['period'] ?? 'last_7_days');
|
||||
$metric = (string) ($filters['metric'] ?? 'overview');
|
||||
$playCode = isset($filters['play_code']) && $filters['play_code'] !== ''
|
||||
@@ -45,7 +52,7 @@ final class AdminDashboardAnalyticsBuilder
|
||||
$dateFrom = $range['date_from'];
|
||||
$dateTo = $range['date_to'];
|
||||
|
||||
$trend = $this->reportQuery->dailyProfitSeriesFilled($dateFrom, $dateTo, scopedAdmin: $admin);
|
||||
$trend = $this->reportQuery->dailyProfitSeriesFilled($dateFrom, $dateTo, scope: $scope);
|
||||
|
||||
return [
|
||||
'period' => $period,
|
||||
@@ -53,8 +60,8 @@ final class AdminDashboardAnalyticsBuilder
|
||||
'play_code' => $playCode,
|
||||
'date_from' => $dateFrom,
|
||||
'date_to' => $dateTo,
|
||||
'currency_code' => $this->reportQuery->resolvePeriodCurrencyCode($dateFrom, $dateTo, $admin),
|
||||
'summary' => $this->reportQuery->periodFinanceTotals($dateFrom, $dateTo, $admin),
|
||||
'currency_code' => $this->reportQuery->resolvePeriodCurrencyCode($dateFrom, $dateTo, $scope),
|
||||
'summary' => $this->reportQuery->periodFinanceTotals($dateFrom, $dateTo, $scope),
|
||||
'daily_series' => $trend['series'],
|
||||
'chart_meta' => [
|
||||
'chart_date_from' => $trend['chart_date_from'],
|
||||
@@ -66,14 +73,14 @@ final class AdminDashboardAnalyticsBuilder
|
||||
$dateFrom,
|
||||
$dateTo,
|
||||
$playCode,
|
||||
scopedAdmin: $admin,
|
||||
scope: $scope,
|
||||
),
|
||||
'agent_breakdown' => $this->reportQuery->agentRankingRows(
|
||||
$dateFrom,
|
||||
$dateTo,
|
||||
$playCode,
|
||||
limit: 200,
|
||||
scopedAdmin: $admin,
|
||||
scope: $scope,
|
||||
),
|
||||
];
|
||||
}
|
||||
@@ -81,6 +88,6 @@ final class AdminDashboardAnalyticsBuilder
|
||||
/** 与 {@see AdminAuthorizationRegistry} 中 dashboard 类 API 资源的 `dashboard.view` 绑定一致。 */
|
||||
private function canView(AdminUser $admin): bool
|
||||
{
|
||||
return $admin->hasAdminPermission('prd.dashboard.view');
|
||||
return $admin->hasPermissionCode('dashboard.view');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,10 @@ use App\Models\DrawResultBatch;
|
||||
use App\Lottery\DrawResultBatchStatus;
|
||||
use App\Services\Draw\DrawHallSnapshotBuilder;
|
||||
use App\Support\AdminDataScope;
|
||||
use App\Support\AdminScopeContext;
|
||||
use App\Support\AdminAgentScope;
|
||||
use App\Support\AdminScopeContextResolver;
|
||||
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
|
||||
|
||||
/**
|
||||
* 后台首页仪表盘:聚合大厅快照、当期财务、期号面板、风控摘要、异常转账计数。
|
||||
@@ -28,8 +32,9 @@ final class AdminDashboardSnapshotBuilder
|
||||
) {}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function build(AdminUser $admin): array
|
||||
public function build(AdminScopeContext $scope): array
|
||||
{
|
||||
$admin = $scope->admin;
|
||||
$hall = $this->hallSnapshot->build();
|
||||
$canDraw = $this->canDrawFinanceAndRisk($admin);
|
||||
$canWallet = $this->canWalletReconcile($admin);
|
||||
@@ -53,11 +58,11 @@ final class AdminDashboardSnapshotBuilder
|
||||
];
|
||||
|
||||
if ($canDraw) {
|
||||
$this->fillPlatformOverview($out, $admin);
|
||||
$this->fillPlatformOverview($out, $scope);
|
||||
}
|
||||
|
||||
if ($canWallet) {
|
||||
$out['abnormal_transfer_total'] = $this->abnormalTransferTotal($admin);
|
||||
$out['abnormal_transfer_total'] = $this->abnormalTransferTotal($scope);
|
||||
}
|
||||
|
||||
if ($hall === null) {
|
||||
@@ -82,7 +87,7 @@ final class AdminDashboardSnapshotBuilder
|
||||
];
|
||||
|
||||
if ($canDraw) {
|
||||
$out['finance'] = $this->financeSummary($draw, $admin);
|
||||
$out['finance'] = $this->financeSummary($draw, $scope);
|
||||
$out['draw'] = $this->drawPanel($draw);
|
||||
$out['risk'] = $this->riskPanel($draw);
|
||||
}
|
||||
@@ -91,35 +96,48 @@ final class AdminDashboardSnapshotBuilder
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $out */
|
||||
private function fillPlatformOverview(array &$out, AdminUser $admin): void
|
||||
private function fillPlatformOverview(array &$out, AdminScopeContext $scope): void
|
||||
{
|
||||
$out['today_finance'] = $this->todayFinanceSummary($admin);
|
||||
$out['lifetime_finance'] = $this->reportQuery->platformLifetimeTotals($admin);
|
||||
$out['platform_risk'] = $this->platformRiskSummary();
|
||||
$out['result_batch_queue'] = $this->resultBatchQueue();
|
||||
$admin = $scope->admin;
|
||||
$out['today_finance'] = $this->todayFinanceSummary($scope);
|
||||
$out['lifetime_finance'] = $this->reportQuery->platformLifetimeTotals(
|
||||
$scope,
|
||||
);
|
||||
|
||||
if ($admin->isSuperAdmin()
|
||||
&& $scope->effectiveRequestedSiteCode() === null
|
||||
&& $scope->effectiveRequestedAgentNodeId() === null
|
||||
) {
|
||||
$out['platform_risk'] = $this->platformRiskSummary();
|
||||
$out['result_batch_queue'] = $this->resultBatchQueue();
|
||||
}
|
||||
}
|
||||
|
||||
private function canDrawFinanceAndRisk(AdminUser $admin): bool
|
||||
{
|
||||
return $admin->hasAdminPermission('prd.dashboard.view')
|
||||
|| $admin->hasAdminPermission('prd.draw_result.manage')
|
||||
|| $admin->hasAdminPermission('prd.draw_result.view')
|
||||
|| $admin->hasAdminPermission('prd.risk.view')
|
||||
|| $admin->hasAdminPermission('prd.risk.manage');
|
||||
return $admin->hasPermissionCode('dashboard.view')
|
||||
|| $admin->hasPermissionCode('draw.results.view')
|
||||
|| $admin->hasPermissionCode('draw.review.review')
|
||||
|| $admin->hasPermissionCode('draw.review.publish')
|
||||
|| $admin->hasPermissionCode('risk.monitor.view')
|
||||
|| $admin->hasPermissionCode('risk.monitor.manage');
|
||||
}
|
||||
|
||||
private function canWalletReconcile(AdminUser $admin): bool
|
||||
{
|
||||
return $admin->hasAdminPermission('prd.wallet_reconcile.manage')
|
||||
|| $admin->hasAdminPermission('prd.wallet_reconcile.view')
|
||||
|| $admin->hasAdminPermission('prd.wallet_reconcile.view_cs');
|
||||
return $admin->hasPermissionCode('service.reconcile.manage')
|
||||
|| $admin->hasPermissionCode('service.reconcile.view')
|
||||
|| $admin->hasPermissionCode('service.wallet.view')
|
||||
|| $admin->hasPermissionCode('service.wallet.manage');
|
||||
}
|
||||
|
||||
private function abnormalTransferTotal(AdminUser $admin): int
|
||||
private function abnormalTransferTotal(AdminScopeContext $scope): int
|
||||
{
|
||||
$admin = $scope->admin;
|
||||
$query = TransferOrder::query()
|
||||
->whereIn('status', ['processing', 'failed', 'pending_reconcile']);
|
||||
AdminDataScope::applyEloquentViaPlayer($query, $admin);
|
||||
$this->applyRequestedScopeViaPlayer($query, $scope);
|
||||
|
||||
return (int) $query->count();
|
||||
}
|
||||
@@ -129,10 +147,15 @@ final class AdminDashboardSnapshotBuilder
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function todayFinanceSummary(AdminUser $admin): array
|
||||
private function todayFinanceSummary(AdminScopeContext $scope): array
|
||||
{
|
||||
$admin = $scope->admin;
|
||||
$today = now()->toDateString();
|
||||
$rows = $this->reportQuery->dailyProfitRows($today, $today, $admin);
|
||||
$rows = $this->reportQuery->dailyProfitRows(
|
||||
$today,
|
||||
$today,
|
||||
$scope,
|
||||
);
|
||||
$row = $rows[0] ?? [
|
||||
'business_date' => $today,
|
||||
'total_bet_minor' => 0,
|
||||
@@ -140,10 +163,12 @@ final class AdminDashboardSnapshotBuilder
|
||||
'approx_house_gross_minor' => 0,
|
||||
];
|
||||
|
||||
$currencyCode = (string) (TicketOrder::query()
|
||||
$currencyQuery = TicketOrder::query()
|
||||
->join('draws', 'draws.id', '=', 'ticket_orders.draw_id')
|
||||
->where('draws.business_date', $today)
|
||||
->value('ticket_orders.currency_code') ?? '');
|
||||
->where('draws.business_date', $today);
|
||||
AdminDataScope::applyEloquentViaPlayer($currencyQuery, $admin);
|
||||
$this->applyRequestedScopeViaPlayer($currencyQuery, $scope);
|
||||
$currencyCode = (string) ($currencyQuery->value('ticket_orders.currency_code') ?? '');
|
||||
|
||||
return [
|
||||
'business_date' => (string) $row['business_date'],
|
||||
@@ -155,14 +180,17 @@ final class AdminDashboardSnapshotBuilder
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
private function financeSummary(Draw $draw, AdminUser $admin): array
|
||||
private function financeSummary(Draw $draw, AdminScopeContext $scope): array
|
||||
{
|
||||
$admin = $scope->admin;
|
||||
$drawId = (int) $draw->id;
|
||||
|
||||
$orderQuery = TicketOrder::query()->where('draw_id', $drawId);
|
||||
$itemQuery = TicketItem::query()->where('draw_id', $drawId);
|
||||
AdminDataScope::applyEloquentViaPlayer($orderQuery, $admin);
|
||||
AdminDataScope::applyEloquentViaPlayer($itemQuery, $admin);
|
||||
$this->applyRequestedScopeViaPlayer($orderQuery, $scope);
|
||||
$this->applyRequestedScopeViaPlayer($itemQuery, $scope);
|
||||
|
||||
$totalBetMinor = (int) $orderQuery->sum('total_actual_deduct');
|
||||
$orderCount = (int) $orderQuery->count();
|
||||
@@ -387,4 +415,29 @@ final class AdminDashboardSnapshotBuilder
|
||||
|
||||
return 'other';
|
||||
}
|
||||
|
||||
/**
|
||||
* 叠加全局 scope 参数(site_code / agent_node_id)到 player 关联模型查询。
|
||||
*
|
||||
* @param EloquentBuilder<mixed> $query
|
||||
*/
|
||||
private function applyRequestedScopeViaPlayer(EloquentBuilder $query, AdminScopeContext $scope): void
|
||||
{
|
||||
$siteCode = $scope->effectiveRequestedSiteCode();
|
||||
$agentNodeId = $scope->effectiveRequestedAgentNodeId();
|
||||
if ($siteCode === null && $agentNodeId === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$admin = $scope->admin;
|
||||
$query->whereHas('player', static function (EloquentBuilder $playerQuery) use ($admin, $siteCode, $agentNodeId): void {
|
||||
if ($siteCode !== null) {
|
||||
$playerQuery->where('site_code', $siteCode);
|
||||
}
|
||||
|
||||
if ($agentNodeId !== null) {
|
||||
AdminAgentScope::applyRequestedAgentNodeFilter($playerQuery, $admin, $agentNodeId);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,8 @@ namespace App\Services\Admin;
|
||||
use App\Models\AdminUser;
|
||||
use App\Models\AuditLog;
|
||||
use App\Support\AdminDataScope;
|
||||
use App\Support\AdminScopeContext;
|
||||
use App\Support\AdminScopeContextResolver;
|
||||
use App\Models\Draw;
|
||||
use App\Models\RiskPool;
|
||||
use App\Models\RiskPoolLockLog;
|
||||
@@ -23,6 +25,19 @@ use Illuminate\Support\Facades\DB;
|
||||
*/
|
||||
final class AdminReportQueryService
|
||||
{
|
||||
private function normalizeScope(AdminUser|AdminScopeContext|null $scope): ?AdminScopeContext
|
||||
{
|
||||
if ($scope instanceof AdminScopeContext) {
|
||||
return $scope;
|
||||
}
|
||||
|
||||
if ($scope instanceof AdminUser) {
|
||||
return AdminScopeContextResolver::fromValues($scope);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{date_from: string, date_to: string}
|
||||
*/
|
||||
@@ -111,9 +126,10 @@ final class AdminReportQueryService
|
||||
* business_day_count: int
|
||||
* }
|
||||
*/
|
||||
public function periodFinanceTotals(string $dateFrom, string $dateTo, ?AdminUser $scopedAdmin = null): array
|
||||
public function periodFinanceTotals(string $dateFrom, string $dateTo, AdminUser|AdminScopeContext|null $scope = null): array
|
||||
{
|
||||
$rows = $this->dailyProfitRows($dateFrom, $dateTo, $scopedAdmin);
|
||||
$context = $this->normalizeScope($scope);
|
||||
$rows = $this->dailyProfitRows($dateFrom, $dateTo, $context);
|
||||
$totalBet = 0;
|
||||
$totalPayout = 0;
|
||||
$totalGross = 0;
|
||||
@@ -126,7 +142,7 @@ final class AdminReportQueryService
|
||||
$activityQuery = DB::table('draws as d')
|
||||
->join('ticket_orders as o', 'o.draw_id', '=', 'd.id')
|
||||
->whereBetween('d.business_date', [$dateFrom, $dateTo]);
|
||||
AdminDataScope::applyToTicketOrdersViaPlayer($activityQuery, $scopedAdmin, 'o');
|
||||
AdminDataScope::applyToTicketOrdersViaPlayer($activityQuery, $context?->admin, 'o');
|
||||
$activity = $activityQuery
|
||||
->selectRaw('COUNT(DISTINCT d.id) as draw_count')
|
||||
->selectRaw('COUNT(DISTINCT d.business_date) as business_day_count')
|
||||
@@ -146,8 +162,9 @@ final class AdminReportQueryService
|
||||
*
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public function dailyProfitSeriesFilled(string $dateFrom, string $dateTo, int $maxDays = 90, ?AdminUser $scopedAdmin = null): array
|
||||
public function dailyProfitSeriesFilled(string $dateFrom, string $dateTo, int $maxDays = 90, AdminUser|AdminScopeContext|null $scope = null): array
|
||||
{
|
||||
$context = $this->normalizeScope($scope);
|
||||
$from = Carbon::parse($dateFrom)->startOfDay();
|
||||
$to = Carbon::parse($dateTo)->startOfDay();
|
||||
$spanDays = (int) $from->diffInDays($to) + 1;
|
||||
@@ -160,7 +177,7 @@ final class AdminReportQueryService
|
||||
$truncated = true;
|
||||
}
|
||||
|
||||
$indexed = collect($this->dailyProfitRows($chartFrom, $chartTo, $scopedAdmin))->keyBy('business_date');
|
||||
$indexed = collect($this->dailyProfitRows($chartFrom, $chartTo, $context))->keyBy('business_date');
|
||||
$cursor = Carbon::parse($chartFrom)->startOfDay();
|
||||
$end = Carbon::parse($chartTo)->startOfDay();
|
||||
$series = [];
|
||||
@@ -193,9 +210,9 @@ final class AdminReportQueryService
|
||||
string $dateTo,
|
||||
?string $playCode = null,
|
||||
int $limit = 12,
|
||||
?AdminUser $scopedAdmin = null,
|
||||
AdminUser|AdminScopeContext|null $scope = null,
|
||||
): array {
|
||||
return $this->playDimensionBaseQuery($playCode, $dateFrom, $dateTo, $scopedAdmin)
|
||||
return $this->playDimensionBaseQuery($playCode, $dateFrom, $dateTo, $scope)
|
||||
->orderByDesc('total_bet_minor')
|
||||
->limit($limit)
|
||||
->get()
|
||||
@@ -229,8 +246,9 @@ final class AdminReportQueryService
|
||||
string $dateTo,
|
||||
?string $playCode = null,
|
||||
int $limit = 200,
|
||||
?AdminUser $scopedAdmin = null,
|
||||
AdminUser|AdminScopeContext|null $scope = null,
|
||||
): array {
|
||||
$context = $this->normalizeScope($scope);
|
||||
$query = DB::table('ticket_items as ti')
|
||||
->join('ticket_orders as o', 'o.id', '=', 'ti.order_id')
|
||||
->leftJoin('players as p', 'p.id', '=', 'ti.player_id')
|
||||
@@ -250,7 +268,12 @@ final class AdminReportQueryService
|
||||
$query->where('ti.play_code', $playCode);
|
||||
}
|
||||
|
||||
AdminDataScope::applyToPlayersAlias($query, $scopedAdmin, 'p');
|
||||
AdminDataScope::applyToPlayersAlias(
|
||||
$query,
|
||||
$context?->admin,
|
||||
'p',
|
||||
$context?->effectiveRequestedAgentNodeId(),
|
||||
);
|
||||
|
||||
return $query
|
||||
->orderByDesc('total_bet_minor')
|
||||
@@ -270,20 +293,21 @@ final class AdminReportQueryService
|
||||
->all();
|
||||
}
|
||||
|
||||
public function resolvePeriodCurrencyCode(string $dateFrom, string $dateTo, ?AdminUser $scopedAdmin = null): ?string
|
||||
public function resolvePeriodCurrencyCode(string $dateFrom, string $dateTo, AdminUser|AdminScopeContext|null $scope = null): ?string
|
||||
{
|
||||
$context = $this->normalizeScope($scope);
|
||||
$currencyQuery = DB::table('ticket_orders as o')
|
||||
->join('draws as d', 'd.id', '=', 'o.draw_id')
|
||||
->whereBetween('d.business_date', [$dateFrom, $dateTo]);
|
||||
AdminDataScope::applyToTicketOrdersViaPlayer($currencyQuery, $scopedAdmin, 'o');
|
||||
AdminDataScope::applyToTicketOrdersViaPlayer($currencyQuery, $context?->admin, 'o');
|
||||
$currencyCode = (string) ($currencyQuery->orderByDesc('o.id')->value('o.currency_code') ?? '');
|
||||
|
||||
return $currencyCode !== '' ? $currencyCode : null;
|
||||
}
|
||||
|
||||
public function dailyProfitPaginated(string $dateFrom, string $dateTo, int $page, int $perPage, ?AdminUser $scopedAdmin = null): LengthAwarePaginator
|
||||
public function dailyProfitPaginated(string $dateFrom, string $dateTo, int $page, int $perPage, AdminUser|AdminScopeContext|null $scope = null): LengthAwarePaginator
|
||||
{
|
||||
$rows = $this->dailyProfitRows($dateFrom, $dateTo, $scopedAdmin);
|
||||
$rows = $this->dailyProfitRows($dateFrom, $dateTo, $scope);
|
||||
$total = count($rows);
|
||||
$offset = max(0, ($page - 1) * $perPage);
|
||||
$items = array_slice($rows, $offset, $perPage);
|
||||
@@ -296,18 +320,19 @@ final class AdminReportQueryService
|
||||
/**
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public function dailyProfitRows(string $dateFrom, string $dateTo, ?AdminUser $scopedAdmin = null): array
|
||||
public function dailyProfitRows(string $dateFrom, string $dateTo, AdminUser|AdminScopeContext|null $scope = null): array
|
||||
{
|
||||
$context = $this->normalizeScope($scope);
|
||||
$betSub = DB::table('ticket_orders as o')
|
||||
->selectRaw('o.draw_id, SUM(o.total_actual_deduct) as total_bet_minor')
|
||||
->groupBy('o.draw_id');
|
||||
AdminDataScope::applyToTicketOrdersViaPlayer($betSub, $scopedAdmin, 'o');
|
||||
AdminDataScope::applyToTicketOrdersViaPlayer($betSub, $context?->admin, 'o');
|
||||
|
||||
$payoutSub = DB::table('ticket_items as ti')
|
||||
->join('ticket_orders as o', 'o.id', '=', 'ti.order_id')
|
||||
->selectRaw('ti.draw_id, SUM(ti.win_amount + ti.jackpot_win_amount) as total_payout_minor')
|
||||
->groupBy('ti.draw_id');
|
||||
AdminDataScope::applyToTicketOrdersViaPlayer($payoutSub, $scopedAdmin, 'o');
|
||||
AdminDataScope::applyToTicketOrdersViaPlayer($payoutSub, $context?->admin, 'o');
|
||||
|
||||
return DB::table('draws as d')
|
||||
->whereBetween('d.business_date', [$dateFrom, $dateTo])
|
||||
@@ -351,15 +376,16 @@ final class AdminReportQueryService
|
||||
* date_to: ?string
|
||||
* }
|
||||
*/
|
||||
public function platformLifetimeTotals(?AdminUser $scopedAdmin = null): array
|
||||
public function platformLifetimeTotals(AdminUser|AdminScopeContext|null $scope = null): array
|
||||
{
|
||||
$context = $this->normalizeScope($scope);
|
||||
$betQuery = DB::table('ticket_orders as o');
|
||||
AdminDataScope::applyToTicketOrdersViaPlayer($betQuery, $scopedAdmin, 'o');
|
||||
AdminDataScope::applyToTicketOrdersViaPlayer($betQuery, $context?->admin, 'o');
|
||||
$totalBetMinor = (int) $betQuery->sum('o.total_actual_deduct');
|
||||
|
||||
$payoutQuery = DB::table('ticket_items as ti')
|
||||
->join('ticket_orders as o', 'o.id', '=', 'ti.order_id');
|
||||
AdminDataScope::applyToTicketOrdersViaPlayer($payoutQuery, $scopedAdmin, 'o');
|
||||
AdminDataScope::applyToTicketOrdersViaPlayer($payoutQuery, $context?->admin, 'o');
|
||||
$payoutAgg = $payoutQuery
|
||||
->selectRaw('COALESCE(SUM(ti.win_amount), 0) as win_minor, COALESCE(SUM(ti.jackpot_win_amount), 0) as jackpot_minor')
|
||||
->first();
|
||||
@@ -369,7 +395,7 @@ final class AdminReportQueryService
|
||||
|
||||
$activityQuery = DB::table('draws as d')
|
||||
->join('ticket_orders as o', 'o.draw_id', '=', 'd.id');
|
||||
AdminDataScope::applyToTicketOrdersViaPlayer($activityQuery, $scopedAdmin, 'o');
|
||||
AdminDataScope::applyToTicketOrdersViaPlayer($activityQuery, $context?->admin, 'o');
|
||||
$activity = $activityQuery
|
||||
->selectRaw('COUNT(DISTINCT d.id) as draw_count')
|
||||
->selectRaw('COUNT(DISTINCT d.business_date) as business_day_count')
|
||||
@@ -384,14 +410,14 @@ final class AdminReportQueryService
|
||||
$dateTo = $this->formatBusinessDateValue($activity?->date_to);
|
||||
|
||||
$currencyQuery = DB::table('ticket_orders as o');
|
||||
AdminDataScope::applyToTicketOrdersViaPlayer($currencyQuery, $scopedAdmin, 'o');
|
||||
AdminDataScope::applyToTicketOrdersViaPlayer($currencyQuery, $context?->admin, 'o');
|
||||
$currencyCode = (string) ($currencyQuery->orderByDesc('o.id')->value('o.currency_code') ?? '');
|
||||
|
||||
$orderCountQuery = DB::table('ticket_orders as o');
|
||||
AdminDataScope::applyToTicketOrdersViaPlayer($orderCountQuery, $scopedAdmin, 'o');
|
||||
AdminDataScope::applyToTicketOrdersViaPlayer($orderCountQuery, $context?->admin, 'o');
|
||||
$itemCountQuery = DB::table('ticket_items as ti')
|
||||
->join('ticket_orders as o', 'o.id', '=', 'ti.order_id');
|
||||
AdminDataScope::applyToTicketOrdersViaPlayer($itemCountQuery, $scopedAdmin, 'o');
|
||||
AdminDataScope::applyToTicketOrdersViaPlayer($itemCountQuery, $context?->admin, 'o');
|
||||
|
||||
return [
|
||||
'currency_code' => $currencyCode !== '' ? $currencyCode : null,
|
||||
@@ -415,10 +441,9 @@ final class AdminReportQueryService
|
||||
string $dateTo,
|
||||
int $page,
|
||||
int $perPage,
|
||||
?AdminUser $scopedAdmin = null,
|
||||
?int $requestedAgentNodeId = null,
|
||||
AdminUser|AdminScopeContext|null $scope = null,
|
||||
): LengthAwarePaginator {
|
||||
$query = $this->playerWinLossBaseQuery($playerId, $dateFrom, $dateTo, $scopedAdmin, $requestedAgentNodeId);
|
||||
$query = $this->playerWinLossBaseQuery($playerId, $dateFrom, $dateTo, $scope);
|
||||
|
||||
return $query->paginate($perPage, ['*'], 'page', $page);
|
||||
}
|
||||
@@ -429,9 +454,9 @@ final class AdminReportQueryService
|
||||
string $dateTo,
|
||||
int $page,
|
||||
int $perPage,
|
||||
?AdminUser $scopedAdmin = null,
|
||||
AdminUser|AdminScopeContext|null $scope = null,
|
||||
): LengthAwarePaginator {
|
||||
$query = $this->playDimensionBaseQuery($playCode, $dateFrom, $dateTo, $scopedAdmin);
|
||||
$query = $this->playDimensionBaseQuery($playCode, $dateFrom, $dateTo, $scope);
|
||||
|
||||
return $query->paginate($perPage, ['*'], 'page', $page);
|
||||
}
|
||||
@@ -442,9 +467,9 @@ final class AdminReportQueryService
|
||||
string $dateTo,
|
||||
int $page,
|
||||
int $perPage,
|
||||
?AdminUser $scopedAdmin = null,
|
||||
AdminUser|AdminScopeContext|null $scope = null,
|
||||
): LengthAwarePaginator {
|
||||
$query = $this->rebateCommissionBaseQuery($playCode, $dateFrom, $dateTo, $scopedAdmin);
|
||||
$query = $this->rebateCommissionBaseQuery($playCode, $dateFrom, $dateTo, $scope);
|
||||
|
||||
return $query->paginate($perPage, ['*'], 'page', $page);
|
||||
}
|
||||
@@ -452,21 +477,21 @@ final class AdminReportQueryService
|
||||
/**
|
||||
* @return list<array<int, string|int|float|null>>
|
||||
*/
|
||||
public function reportRows(string $reportType, ?array $filterJson, ?AdminUser $scopedAdmin = null): array
|
||||
public function reportRows(string $reportType, ?array $filterJson, AdminUser|AdminScopeContext|null $scope = null): array
|
||||
{
|
||||
$range = $this->resolveDateRange($filterJson);
|
||||
$dateFrom = $range['date_from'];
|
||||
$dateTo = $range['date_to'];
|
||||
|
||||
return match ($reportType) {
|
||||
'draw_profit_summary' => $this->drawProfitExportRows($filterJson, $scopedAdmin),
|
||||
'daily_profit_summary' => $this->dailyProfitExportRows($dateFrom, $dateTo, $scopedAdmin),
|
||||
'player_win_loss' => $this->playerWinLossExportRows($filterJson, $dateFrom, $dateTo, $scopedAdmin),
|
||||
'play_dimension_report' => $this->playDimensionExportRows($filterJson, $dateFrom, $dateTo, $scopedAdmin),
|
||||
'rebate_commission_report' => $this->rebateCommissionExportRows($filterJson, $dateFrom, $dateTo, $scopedAdmin),
|
||||
'draw_profit_summary' => $this->drawProfitExportRows($filterJson, $scope),
|
||||
'daily_profit_summary' => $this->dailyProfitExportRows($dateFrom, $dateTo, $scope),
|
||||
'player_win_loss' => $this->playerWinLossExportRows($filterJson, $dateFrom, $dateTo, $scope),
|
||||
'play_dimension_report' => $this->playDimensionExportRows($filterJson, $dateFrom, $dateTo, $scope),
|
||||
'rebate_commission_report' => $this->rebateCommissionExportRows($filterJson, $dateFrom, $dateTo, $scope),
|
||||
'audit_operation_report' => $this->auditExportRows($filterJson, $dateFrom, $dateTo),
|
||||
'wallet_transfer_report', 'transfer_orders_daily' => $this->transferOrdersExportRows($filterJson, $dateFrom, $dateTo, $scopedAdmin),
|
||||
'wallet_txns_daily' => $this->walletTxnsExportRows($filterJson, $dateFrom, $dateTo, $scopedAdmin),
|
||||
'wallet_transfer_report', 'transfer_orders_daily' => $this->transferOrdersExportRows($filterJson, $dateFrom, $dateTo, $scope),
|
||||
'wallet_txns_daily' => $this->walletTxnsExportRows($filterJson, $dateFrom, $dateTo, $scope),
|
||||
'hot_number_risk_report' => $this->hotNumberRiskExportRows($filterJson),
|
||||
'sold_out_number_report' => $this->soldOutNumberExportRows($filterJson),
|
||||
default => [
|
||||
@@ -513,12 +538,12 @@ final class AdminReportQueryService
|
||||
/**
|
||||
* @return list<array<int, string|int|float|null>>
|
||||
*/
|
||||
private function dailyProfitExportRows(string $dateFrom, string $dateTo, ?AdminUser $scopedAdmin = null): array
|
||||
private function dailyProfitExportRows(string $dateFrom, string $dateTo, AdminUser|AdminScopeContext|null $scope = null): array
|
||||
{
|
||||
$rows = [
|
||||
['日期', '下注', '派彩', '盈亏'],
|
||||
];
|
||||
foreach ($this->dailyProfitRows($dateFrom, $dateTo, $scopedAdmin) as $row) {
|
||||
foreach ($this->dailyProfitRows($dateFrom, $dateTo, $scope) as $row) {
|
||||
$rows[] = [
|
||||
$row['business_date'],
|
||||
$row['total_bet_minor'],
|
||||
@@ -533,13 +558,13 @@ final class AdminReportQueryService
|
||||
/**
|
||||
* @return list<array<int, string|int|float|null>>
|
||||
*/
|
||||
private function playerWinLossExportRows(?array $filterJson, string $dateFrom, string $dateTo, ?AdminUser $scopedAdmin = null): array
|
||||
private function playerWinLossExportRows(?array $filterJson, string $dateFrom, string $dateTo, AdminUser|AdminScopeContext|null $scope = null): array
|
||||
{
|
||||
$playerId = isset($filterJson['player_id']) ? (int) $filterJson['player_id'] : null;
|
||||
$rows = [
|
||||
['玩家ID', '用户名', '下注', '派彩', '净输赢'],
|
||||
];
|
||||
$items = $this->playerWinLossBaseQuery($playerId, $dateFrom, $dateTo, $scopedAdmin)->get();
|
||||
$items = $this->playerWinLossBaseQuery($playerId, $dateFrom, $dateTo, $scope)->get();
|
||||
foreach ($items as $row) {
|
||||
$rows[] = [
|
||||
(int) $row->player_id,
|
||||
@@ -556,13 +581,13 @@ final class AdminReportQueryService
|
||||
/**
|
||||
* @return list<array<int, string|int|float|null>>
|
||||
*/
|
||||
private function playDimensionExportRows(?array $filterJson, string $dateFrom, string $dateTo, ?AdminUser $scopedAdmin = null): array
|
||||
private function playDimensionExportRows(?array $filterJson, string $dateFrom, string $dateTo, AdminUser|AdminScopeContext|null $scope = null): array
|
||||
{
|
||||
$playCode = isset($filterJson['play_code']) ? trim((string) $filterJson['play_code']) : null;
|
||||
$rows = [
|
||||
['玩法', '维度', '下注', '派彩', '盈亏'],
|
||||
];
|
||||
$items = $this->playDimensionBaseQuery($playCode !== '' ? $playCode : null, $dateFrom, $dateTo, $scopedAdmin)->get();
|
||||
$items = $this->playDimensionBaseQuery($playCode !== '' ? $playCode : null, $dateFrom, $dateTo, $scope)->get();
|
||||
foreach ($items as $row) {
|
||||
$rows[] = [
|
||||
(string) $row->play_code,
|
||||
@@ -579,13 +604,13 @@ final class AdminReportQueryService
|
||||
/**
|
||||
* @return list<array<int, string|int|float|null>>
|
||||
*/
|
||||
private function rebateCommissionExportRows(?array $filterJson, string $dateFrom, string $dateTo, ?AdminUser $scopedAdmin = null): array
|
||||
private function rebateCommissionExportRows(?array $filterJson, string $dateFrom, string $dateTo, AdminUser|AdminScopeContext|null $scope = null): array
|
||||
{
|
||||
$playCode = isset($filterJson['play_code']) ? trim((string) $filterJson['play_code']) : null;
|
||||
$rows = [
|
||||
['玩法', '回水', '订单数', '注单数'],
|
||||
];
|
||||
$items = $this->rebateCommissionBaseQuery($playCode !== '' ? $playCode : null, $dateFrom, $dateTo, $scopedAdmin)->get();
|
||||
$items = $this->rebateCommissionBaseQuery($playCode !== '' ? $playCode : null, $dateFrom, $dateTo, $scope)->get();
|
||||
foreach ($items as $row) {
|
||||
$rows[] = [
|
||||
(string) $row->play_code,
|
||||
@@ -635,9 +660,9 @@ final class AdminReportQueryService
|
||||
?int $playerId,
|
||||
string $dateFrom,
|
||||
string $dateTo,
|
||||
?AdminUser $scopedAdmin = null,
|
||||
?int $requestedAgentNodeId = null,
|
||||
AdminUser|AdminScopeContext|null $scope = null,
|
||||
) {
|
||||
$context = $this->normalizeScope($scope);
|
||||
$query = DB::table('ticket_items as ti')
|
||||
->join('ticket_orders as o', 'o.id', '=', 'ti.order_id')
|
||||
->leftJoin('players as p', 'p.id', '=', 'ti.player_id')
|
||||
@@ -659,16 +684,20 @@ final class AdminReportQueryService
|
||||
$query->where('ti.player_id', $playerId);
|
||||
}
|
||||
|
||||
if ($scopedAdmin !== null) {
|
||||
AdminDataScope::applyToPlayersAlias($query, $scopedAdmin, 'p', $requestedAgentNodeId);
|
||||
}
|
||||
AdminDataScope::applyToPlayersAlias(
|
||||
$query,
|
||||
$context?->admin,
|
||||
'p',
|
||||
$context?->effectiveRequestedAgentNodeId(),
|
||||
);
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
/** @return \Illuminate\Database\Query\Builder */
|
||||
private function playDimensionBaseQuery(?string $playCode, string $dateFrom, string $dateTo, ?AdminUser $scopedAdmin = null)
|
||||
private function playDimensionBaseQuery(?string $playCode, string $dateFrom, string $dateTo, AdminUser|AdminScopeContext|null $scope = null)
|
||||
{
|
||||
$context = $this->normalizeScope($scope);
|
||||
$query = DB::table('ticket_items as ti')
|
||||
->join('ticket_orders as o', 'o.id', '=', 'ti.order_id')
|
||||
->selectRaw('ti.play_code')
|
||||
@@ -686,14 +715,15 @@ final class AdminReportQueryService
|
||||
$query->where('ti.play_code', $playCode);
|
||||
}
|
||||
|
||||
AdminDataScope::applyToTicketOrdersViaPlayer($query, $scopedAdmin, 'o');
|
||||
AdminDataScope::applyToTicketOrdersViaPlayer($query, $context?->admin, 'o');
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
/** @return \Illuminate\Database\Query\Builder */
|
||||
private function rebateCommissionBaseQuery(?string $playCode, string $dateFrom, string $dateTo, ?AdminUser $scopedAdmin = null)
|
||||
private function rebateCommissionBaseQuery(?string $playCode, string $dateFrom, string $dateTo, AdminUser|AdminScopeContext|null $scope = null)
|
||||
{
|
||||
$context = $this->normalizeScope($scope);
|
||||
$query = DB::table('ticket_items as ti')
|
||||
->join('ticket_orders as o', 'o.id', '=', 'ti.order_id')
|
||||
->selectRaw('ti.play_code')
|
||||
@@ -709,7 +739,7 @@ final class AdminReportQueryService
|
||||
$query->where('ti.play_code', $playCode);
|
||||
}
|
||||
|
||||
AdminDataScope::applyToTicketOrdersViaPlayer($query, $scopedAdmin, 'o');
|
||||
AdminDataScope::applyToTicketOrdersViaPlayer($query, $context?->admin, 'o');
|
||||
|
||||
return $query;
|
||||
}
|
||||
@@ -717,8 +747,9 @@ final class AdminReportQueryService
|
||||
/**
|
||||
* @return list<array<int, string|int|float|null>>
|
||||
*/
|
||||
private function drawProfitExportRows(?array $filterJson, ?AdminUser $scopedAdmin = null): array
|
||||
private function drawProfitExportRows(?array $filterJson, AdminUser|AdminScopeContext|null $scope = null): array
|
||||
{
|
||||
$context = $this->normalizeScope($scope);
|
||||
$draw = $this->resolveDrawForReport($filterJson);
|
||||
if ($draw === null) {
|
||||
return [['提示', '请提供 draw_id 或 draw_no']];
|
||||
@@ -727,9 +758,9 @@ final class AdminReportQueryService
|
||||
$drawId = (int) $draw->id;
|
||||
$orderQuery = TicketOrder::query()->where('draw_id', $drawId);
|
||||
$itemQuery = TicketItem::query()->where('draw_id', $drawId);
|
||||
if ($scopedAdmin !== null) {
|
||||
AdminDataScope::applyEloquentViaPlayer($orderQuery, $scopedAdmin);
|
||||
AdminDataScope::applyEloquentViaPlayer($itemQuery, $scopedAdmin);
|
||||
if ($context !== null) {
|
||||
AdminDataScope::applyEloquentViaPlayer($orderQuery, $context->admin);
|
||||
AdminDataScope::applyEloquentViaPlayer($itemQuery, $context->admin);
|
||||
}
|
||||
|
||||
$totalBetMinor = (int) $orderQuery->sum('total_actual_deduct');
|
||||
@@ -952,8 +983,9 @@ final class AdminReportQueryService
|
||||
/**
|
||||
* @return list<array<int, string|int|float|null>>
|
||||
*/
|
||||
private function transferOrdersExportRows(?array $filterJson, string $dateFrom, string $dateTo, ?AdminUser $scopedAdmin = null): array
|
||||
private function transferOrdersExportRows(?array $filterJson, string $dateFrom, string $dateTo, AdminUser|AdminScopeContext|null $scope = null): array
|
||||
{
|
||||
$context = $this->normalizeScope($scope);
|
||||
$rows = [
|
||||
['转账单号', '玩家ID', '用户名', '昵称', '方向', '币种', '金额', '状态', '外部单号', '失败原因', '创建时间', '完成时间'],
|
||||
];
|
||||
@@ -962,8 +994,8 @@ final class AdminReportQueryService
|
||||
->with(['player:id,username,nickname'])
|
||||
->orderByDesc('id');
|
||||
|
||||
if ($scopedAdmin !== null) {
|
||||
AdminDataScope::applyEloquentViaPlayer($query, $scopedAdmin);
|
||||
if ($context !== null) {
|
||||
AdminDataScope::applyEloquentViaPlayer($query, $context->admin);
|
||||
}
|
||||
|
||||
$playerId = isset($filterJson['player_id']) ? (int) $filterJson['player_id'] : null;
|
||||
@@ -998,8 +1030,9 @@ final class AdminReportQueryService
|
||||
/**
|
||||
* @return list<array<int, string|int|float|null>>
|
||||
*/
|
||||
private function walletTxnsExportRows(?array $filterJson, string $dateFrom, string $dateTo, ?AdminUser $scopedAdmin = null): array
|
||||
private function walletTxnsExportRows(?array $filterJson, string $dateFrom, string $dateTo, AdminUser|AdminScopeContext|null $scope = null): array
|
||||
{
|
||||
$context = $this->normalizeScope($scope);
|
||||
$rows = [
|
||||
['流水号', '玩家ID', '用户名', '业务类型', '业务单号', '方向', '金额', '变动前余额', '变动后余额', '状态', '外部单号', '备注', '创建时间'],
|
||||
];
|
||||
@@ -1008,8 +1041,8 @@ final class AdminReportQueryService
|
||||
->with(['player:id,username'])
|
||||
->orderByDesc('id');
|
||||
|
||||
if ($scopedAdmin !== null) {
|
||||
AdminDataScope::applyEloquentViaPlayer($query, $scopedAdmin);
|
||||
if ($context !== null) {
|
||||
AdminDataScope::applyEloquentViaPlayer($query, $context->admin);
|
||||
}
|
||||
|
||||
$playerId = isset($filterJson['player_id']) ? (int) $filterJson['player_id'] : null;
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace App\Services\Agent;
|
||||
use App\Models\AdminRole;
|
||||
use App\Models\AdminUser;
|
||||
use App\Models\AgentNode;
|
||||
use App\Support\AdminPermissionInheritance;
|
||||
use App\Support\AgentRoleAuthorization;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
@@ -16,10 +17,14 @@ final class AgentRoleService
|
||||
*/
|
||||
public function createForAgent(AdminUser $actor, AgentNode $owner, array $payload): AdminRole
|
||||
{
|
||||
$permissionSlugs = AdminPermissionInheritance::expand(
|
||||
array_values(array_unique($payload['permission_slugs'] ?? [])),
|
||||
);
|
||||
|
||||
AgentRoleAuthorization::assertSlugsForAgentRole(
|
||||
$actor,
|
||||
$owner,
|
||||
array_values(array_unique($payload['permission_slugs'] ?? [])),
|
||||
$permissionSlugs,
|
||||
);
|
||||
|
||||
$slug = trim((string) $payload['slug']);
|
||||
@@ -30,7 +35,7 @@ final class AgentRoleService
|
||||
throw ValidationException::withMessages(['slug' => ['unique']]);
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($payload, $owner, $slug): AdminRole {
|
||||
return DB::transaction(function () use ($payload, $owner, $slug, $permissionSlugs): AdminRole {
|
||||
$role = AdminRole::query()->create([
|
||||
'slug' => $slug,
|
||||
'code' => $slug,
|
||||
@@ -44,7 +49,7 @@ final class AgentRoleService
|
||||
'delegated_from_role_id' => null,
|
||||
]);
|
||||
|
||||
$role->syncLegacyPermissionSlugs($payload['permission_slugs'] ?? []);
|
||||
$role->syncLegacyPermissionSlugs($permissionSlugs);
|
||||
|
||||
return $role->fresh();
|
||||
});
|
||||
@@ -80,6 +85,7 @@ final class AgentRoleService
|
||||
*/
|
||||
public function syncPermissions(AdminUser $actor, AdminRole $role, array $permissionSlugs): AdminRole
|
||||
{
|
||||
$permissionSlugs = AdminPermissionInheritance::expand($permissionSlugs);
|
||||
$owner = AgentNode::query()->findOrFail((int) $role->owner_agent_id);
|
||||
AgentRoleAuthorization::assertSlugsForAgentRole($actor, $owner, $permissionSlugs);
|
||||
$role->syncLegacyPermissionSlugs($permissionSlugs);
|
||||
|
||||
@@ -6,6 +6,7 @@ use App\Models\Player;
|
||||
use App\Models\AuditLog;
|
||||
use App\Models\AdminUser;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Http\Middleware\RecordAdminApiAudit;
|
||||
|
||||
/**
|
||||
* 审计日志写入入口:落到表 audit_logs,仅 created_at。
|
||||
@@ -70,7 +71,7 @@ final class AuditLogger
|
||||
?array $beforeJson = null,
|
||||
?array $afterJson = null,
|
||||
): AuditLog {
|
||||
return self::record(
|
||||
$row = self::record(
|
||||
$operatorType,
|
||||
$operatorId,
|
||||
$moduleCode,
|
||||
@@ -82,6 +83,24 @@ final class AuditLogger
|
||||
$request->ip(),
|
||||
$request->userAgent(),
|
||||
);
|
||||
|
||||
self::markAdminApiAuditRecorded($request);
|
||||
|
||||
return $row;
|
||||
}
|
||||
|
||||
/** 业务层已写审计时,避免 {@see RecordAdminApiAudit} 重复落库(FormRequest 可能与管道中的 Request 非同一实例)。 */
|
||||
public static function markAdminApiAuditRecorded(Request $request): void
|
||||
{
|
||||
$request->attributes->set(RecordAdminApiAudit::ATTRIBUTE_AUDIT_RECORDED, true);
|
||||
|
||||
try {
|
||||
$resolved = request();
|
||||
if ($resolved !== $request) {
|
||||
$resolved->attributes->set(RecordAdminApiAudit::ATTRIBUTE_AUDIT_RECORDED, true);
|
||||
}
|
||||
} catch (\Throwable) {
|
||||
}
|
||||
}
|
||||
|
||||
public static function recordForAdmin(AdminUser $admin, ?Request $request = null, ?string $moduleCode = null, ?string $actionCode = null, ?string $targetType = null, ?string $targetId = null, ?array $beforeJson = null, ?array $afterJson = null): AuditLog
|
||||
|
||||
@@ -86,6 +86,8 @@ final class DrawCancelBetRefundService
|
||||
$this->ticketWallet->reverseBetDeduct($lockedOrder);
|
||||
}
|
||||
|
||||
$this->ticketWallet->releaseReservedBetDeduct($lockedOrder, 'draw_cancelled_release');
|
||||
|
||||
$lockedOrder->forceFill(['status' => 'refunded'])->save();
|
||||
}
|
||||
}
|
||||
|
||||
120
app/Services/Settlement/SettlementPayoutCorrectionService.php
Normal file
120
app/Services/Settlement/SettlementPayoutCorrectionService.php
Normal file
@@ -0,0 +1,120 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Settlement;
|
||||
|
||||
use App\Models\Player;
|
||||
use App\Models\AdminUser;
|
||||
use App\Services\AuditLogger;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Models\SettlementBatch;
|
||||
use App\Models\TicketSettlementDetail;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use App\Services\Ticket\TicketWalletService;
|
||||
use App\Http\Middleware\RecordAdminApiAudit;
|
||||
use App\Lottery\SettlementBatchStatus;
|
||||
|
||||
final class SettlementPayoutCorrectionService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly TicketWalletService $walletService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function apply(
|
||||
SettlementBatch $batch,
|
||||
AdminUser $admin,
|
||||
int $playerId,
|
||||
int $amountDelta,
|
||||
string $reason,
|
||||
Request $request,
|
||||
): array {
|
||||
return DB::transaction(function () use ($batch, $admin, $playerId, $amountDelta, $reason, $request): array {
|
||||
/** @var SettlementBatch $lockedBatch */
|
||||
$lockedBatch = SettlementBatch::query()->whereKey($batch->id)->lockForUpdate()->firstOrFail();
|
||||
if ($lockedBatch->status !== SettlementBatchStatus::Paid->value) {
|
||||
throw new \RuntimeException('settlement_batch_not_paid');
|
||||
}
|
||||
|
||||
$detail = TicketSettlementDetail::query()
|
||||
->where('settlement_batch_id', $lockedBatch->id)
|
||||
->whereHas('ticketItem', fn ($query) => $query->where('player_id', $playerId))
|
||||
->with(['ticketItem.order'])
|
||||
->orderBy('id')
|
||||
->first();
|
||||
|
||||
if ($detail === null || $detail->ticketItem === null) {
|
||||
throw new \RuntimeException('settlement_player_not_in_batch');
|
||||
}
|
||||
|
||||
$player = Player::query()->whereKey($playerId)->firstOrFail();
|
||||
$currencyCode = strtoupper((string) ($detail->ticketItem->order?->currency_code ?? 'NPR'));
|
||||
$correctionNo = $this->newCorrectionNo();
|
||||
$remark = sprintf(
|
||||
'settlement_batch_adjustment:%d:%d:%s',
|
||||
(int) $lockedBatch->id,
|
||||
$playerId,
|
||||
mb_substr(trim($reason), 0, 180)
|
||||
);
|
||||
|
||||
$before = [
|
||||
'batch_id' => (int) $lockedBatch->id,
|
||||
'batch_status' => (string) $lockedBatch->status,
|
||||
'player_id' => $playerId,
|
||||
'currency_code' => $currencyCode,
|
||||
'amount_delta' => $amountDelta,
|
||||
'reason' => $reason,
|
||||
'ticket_item_id' => (int) $detail->ticket_item_id,
|
||||
'ticket_no' => (string) ($detail->ticketItem->ticket_no ?? ''),
|
||||
'original_win_amount' => (int) $detail->win_amount,
|
||||
'original_jackpot_allocation_amount' => (int) $detail->jackpot_allocation_amount,
|
||||
];
|
||||
|
||||
$txnNo = $this->walletService->applySettlementCorrection(
|
||||
$player,
|
||||
$currencyCode,
|
||||
$amountDelta,
|
||||
$correctionNo,
|
||||
$remark,
|
||||
);
|
||||
|
||||
AuditLogger::recordForAdmin(
|
||||
$admin,
|
||||
$request,
|
||||
moduleCode: 'settlement',
|
||||
actionCode: 'payout_adjustment',
|
||||
targetType: 'settlement_batch_adjustment',
|
||||
targetId: $correctionNo,
|
||||
beforeJson: $before,
|
||||
afterJson: [
|
||||
'batch_id' => (int) $lockedBatch->id,
|
||||
'player_id' => $playerId,
|
||||
'currency_code' => $currencyCode,
|
||||
'amount_delta' => $amountDelta,
|
||||
'direction' => $amountDelta > 0 ? 'credit' : 'debit',
|
||||
'reason' => $reason,
|
||||
'correction_no' => $correctionNo,
|
||||
'wallet_txn_no' => $txnNo,
|
||||
],
|
||||
);
|
||||
$request->attributes->set(RecordAdminApiAudit::ATTRIBUTE_AUDIT_RECORDED, true);
|
||||
|
||||
return [
|
||||
'batch_id' => (int) $lockedBatch->id,
|
||||
'player_id' => $playerId,
|
||||
'currency_code' => $currencyCode,
|
||||
'amount_delta' => $amountDelta,
|
||||
'direction' => $amountDelta > 0 ? 'credit' : 'debit',
|
||||
'reason' => $reason,
|
||||
'correction_no' => $correctionNo,
|
||||
'wallet_txn_no' => $txnNo,
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
private function newCorrectionNo(): string
|
||||
{
|
||||
return 'SC'.now()->format('YmdHis').str_pad((string) random_int(0, 999999), 6, '0', STR_PAD_LEFT);
|
||||
}
|
||||
}
|
||||
@@ -124,6 +124,8 @@ final class TicketPendingConfirmReconcileService
|
||||
$this->ticketWallet->reverseBetDeduct($lockedOrder);
|
||||
}
|
||||
|
||||
$this->ticketWallet->releaseReservedBetDeduct($lockedOrder, $reasonCode.'_release');
|
||||
|
||||
return $this->refundPendingConfirmItems($lockedOrder, $reasonCode);
|
||||
}
|
||||
|
||||
|
||||
@@ -297,6 +297,13 @@ final class TicketPlacementService
|
||||
'status' => $failedItems === [] ? 'pending_confirm' : 'partial_pending_confirm',
|
||||
])->save();
|
||||
|
||||
$this->ticketWalletService->reserveBetDeduct(
|
||||
$player,
|
||||
$currencyCode,
|
||||
$successTotalActualDeduct,
|
||||
$order,
|
||||
);
|
||||
|
||||
return [
|
||||
'order' => $order,
|
||||
'draw_id' => (int) $draw->id,
|
||||
@@ -317,7 +324,12 @@ final class TicketPlacementService
|
||||
$draw = Draw::query()->whereKey((int) $placement['draw_id'])->firstOrFail();
|
||||
|
||||
try {
|
||||
$balanceAfter = $this->ticketWalletService->deduct($player, (string) $placement['currency_code'], (int) $placement['success_total_actual_deduct'], $order);
|
||||
$balanceAfter = $this->ticketWalletService->finalizeReservedBetDeduct(
|
||||
$player,
|
||||
(string) $placement['currency_code'],
|
||||
(int) $placement['success_total_actual_deduct'],
|
||||
$order,
|
||||
);
|
||||
|
||||
DB::transaction(function () use ($order, $draw, $placement): void {
|
||||
$successfulItems = TicketItem::query()
|
||||
@@ -361,6 +373,7 @@ final class TicketPlacementService
|
||||
}
|
||||
|
||||
$order->forceFill(['status' => 'refunded'])->save();
|
||||
$this->ticketWalletService->releaseReservedBetDeduct($order, 'wallet_deduct_failed_release');
|
||||
$this->ticketWalletService->reverseBetDeduct($order);
|
||||
});
|
||||
|
||||
|
||||
@@ -2,12 +2,12 @@
|
||||
|
||||
namespace App\Services\Ticket;
|
||||
|
||||
use App\Models\Player;
|
||||
use App\Models\WalletTxn;
|
||||
use App\Lottery\ErrorCode;
|
||||
use App\Models\TicketOrder;
|
||||
use App\Models\PlayerWallet;
|
||||
use App\Exceptions\TicketOperationException;
|
||||
use App\Lottery\ErrorCode;
|
||||
use App\Models\Player;
|
||||
use App\Models\PlayerWallet;
|
||||
use App\Models\TicketOrder;
|
||||
use App\Models\WalletTxn;
|
||||
use App\Services\Wallet\WalletBalanceRealtimeNotifier;
|
||||
|
||||
final class TicketWalletService
|
||||
@@ -15,47 +15,90 @@ final class TicketWalletService
|
||||
public function __construct(
|
||||
private readonly WalletBalanceRealtimeNotifier $balanceRealtime,
|
||||
) {}
|
||||
|
||||
private const TXN_POSTED = 'posted';
|
||||
|
||||
private const TXN_DIR_OUT = 2;
|
||||
|
||||
private const TXN_DIR_IN = 1;
|
||||
|
||||
public function deduct(Player $player, string $currencyCode, int $amountMinor, TicketOrder $order): int
|
||||
private const BIZ_BET_RESERVE = 'bet_reserve';
|
||||
|
||||
private const BIZ_BET_RESERVE_RELEASE = 'bet_reserve_release';
|
||||
|
||||
public function reserveBetDeduct(Player $player, string $currencyCode, int $amountMinor, TicketOrder $order): void
|
||||
{
|
||||
$wallet = PlayerWallet::query()
|
||||
->where('player_id', $player->id)
|
||||
->where('wallet_type', 'lottery')
|
||||
->where('currency_code', strtoupper($currencyCode))
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($wallet === null) {
|
||||
$wallet = PlayerWallet::query()->create([
|
||||
'player_id' => $player->id,
|
||||
'wallet_type' => 'lottery',
|
||||
'currency_code' => strtoupper($currencyCode),
|
||||
'balance' => 0,
|
||||
'frozen_balance' => 0,
|
||||
'status' => 0,
|
||||
'version' => 0,
|
||||
]);
|
||||
$wallet = PlayerWallet::query()->whereKey($wallet->id)->lockForUpdate()->firstOrFail();
|
||||
if ($amountMinor <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ((int) $wallet->status !== 0) {
|
||||
throw new TicketOperationException('wallet_frozen', ErrorCode::WalletLotteryFrozen->value);
|
||||
$idempotentKey = self::BIZ_BET_RESERVE.':'.$order->order_no;
|
||||
if (WalletTxn::query()->where('biz_type', self::BIZ_BET_RESERVE)->where('idempotent_key', $idempotentKey)->exists()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$wallet = $this->lockOrCreateWallet($player, $currencyCode);
|
||||
$before = (int) $wallet->balance;
|
||||
$available = $before - (int) $wallet->frozen_balance;
|
||||
$frozenBefore = (int) $wallet->frozen_balance;
|
||||
$available = $before - $frozenBefore;
|
||||
if ($available < $amountMinor) {
|
||||
throw new TicketOperationException('bet_insufficient_balance', ErrorCode::BetInsufficientBalance->value);
|
||||
}
|
||||
|
||||
$wallet->forceFill([
|
||||
'frozen_balance' => $frozenBefore + $amountMinor,
|
||||
'version' => (int) $wallet->version + 1,
|
||||
])->save();
|
||||
|
||||
WalletTxn::query()->create([
|
||||
'txn_no' => $this->newTxnNo(),
|
||||
'player_id' => $player->id,
|
||||
'wallet_id' => $wallet->id,
|
||||
'biz_type' => self::BIZ_BET_RESERVE,
|
||||
'biz_no' => $order->order_no,
|
||||
'direction' => self::TXN_DIR_OUT,
|
||||
'amount' => $amountMinor,
|
||||
'balance_before' => $before,
|
||||
'balance_after' => $before,
|
||||
'status' => self::TXN_POSTED,
|
||||
'external_ref_no' => null,
|
||||
'idempotent_key' => $idempotentKey,
|
||||
'remark' => 'pending_confirm_reserve',
|
||||
]);
|
||||
}
|
||||
|
||||
public function finalizeReservedBetDeduct(Player $player, string $currencyCode, int $amountMinor, TicketOrder $order): int
|
||||
{
|
||||
if ($amountMinor <= 0) {
|
||||
$wallet = PlayerWallet::query()
|
||||
->where('player_id', $player->id)
|
||||
->where('wallet_type', 'lottery')
|
||||
->where('currency_code', strtoupper($currencyCode))
|
||||
->first();
|
||||
|
||||
return $wallet !== null ? (int) $wallet->balance : 0;
|
||||
}
|
||||
|
||||
$deductIdempotentKey = 'bet_deduct:'.$order->order_no;
|
||||
$existingDeduct = WalletTxn::query()
|
||||
->where('biz_type', 'bet_deduct')
|
||||
->where('idempotent_key', $deductIdempotentKey)
|
||||
->first();
|
||||
if ($existingDeduct !== null) {
|
||||
return (int) $existingDeduct->balance_after;
|
||||
}
|
||||
|
||||
$wallet = $this->lockOrCreateWallet($player, $currencyCode);
|
||||
$before = (int) $wallet->balance;
|
||||
$frozenBefore = (int) $wallet->frozen_balance;
|
||||
if ($frozenBefore < $amountMinor) {
|
||||
throw new TicketOperationException('bet_reserve_missing', ErrorCode::BetInsufficientBalance->value);
|
||||
}
|
||||
|
||||
$after = $before - $amountMinor;
|
||||
$wallet->forceFill([
|
||||
'balance' => $after,
|
||||
'frozen_balance' => $frozenBefore - $amountMinor,
|
||||
'version' => (int) $wallet->version + 1,
|
||||
])->save();
|
||||
|
||||
@@ -71,7 +114,7 @@ final class TicketWalletService
|
||||
'balance_after' => $after,
|
||||
'status' => self::TXN_POSTED,
|
||||
'external_ref_no' => null,
|
||||
'idempotent_key' => 'bet_deduct:'.$order->order_no,
|
||||
'idempotent_key' => $deductIdempotentKey,
|
||||
'remark' => null,
|
||||
]);
|
||||
|
||||
@@ -81,6 +124,63 @@ final class TicketWalletService
|
||||
return $after;
|
||||
}
|
||||
|
||||
public function releaseReservedBetDeduct(TicketOrder $order, string $remark = 'pending_confirm_release'): void
|
||||
{
|
||||
$reserveIdempotentKey = self::BIZ_BET_RESERVE.':'.$order->order_no;
|
||||
$releaseIdempotentKey = self::BIZ_BET_RESERVE_RELEASE.':'.$order->order_no;
|
||||
|
||||
if (! WalletTxn::query()->where('biz_type', self::BIZ_BET_RESERVE)->where('idempotent_key', $reserveIdempotentKey)->exists()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (WalletTxn::query()->where('biz_type', 'bet_deduct')->where('biz_no', $order->order_no)->where('status', self::TXN_POSTED)->exists()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (WalletTxn::query()->where('biz_type', self::BIZ_BET_RESERVE_RELEASE)->where('idempotent_key', $releaseIdempotentKey)->exists()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$wallet = PlayerWallet::query()
|
||||
->where('player_id', $order->player_id)
|
||||
->where('wallet_type', 'lottery')
|
||||
->where('currency_code', strtoupper((string) $order->currency_code))
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($wallet === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$before = (int) $wallet->balance;
|
||||
$frozenBefore = (int) $wallet->frozen_balance;
|
||||
$releaseAmount = min($frozenBefore, (int) $order->total_actual_deduct);
|
||||
if ($releaseAmount <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
$wallet->forceFill([
|
||||
'frozen_balance' => $frozenBefore - $releaseAmount,
|
||||
'version' => (int) $wallet->version + 1,
|
||||
])->save();
|
||||
|
||||
WalletTxn::query()->create([
|
||||
'txn_no' => $this->newTxnNo(),
|
||||
'player_id' => (int) $order->player_id,
|
||||
'wallet_id' => $wallet->id,
|
||||
'biz_type' => self::BIZ_BET_RESERVE_RELEASE,
|
||||
'biz_no' => $order->order_no,
|
||||
'direction' => self::TXN_DIR_IN,
|
||||
'amount' => $releaseAmount,
|
||||
'balance_before' => $before,
|
||||
'balance_after' => $before,
|
||||
'status' => self::TXN_POSTED,
|
||||
'external_ref_no' => null,
|
||||
'idempotent_key' => $releaseIdempotentKey,
|
||||
'remark' => $remark,
|
||||
]);
|
||||
}
|
||||
|
||||
public function reverseBetDeduct(TicketOrder $order): void
|
||||
{
|
||||
$deductTxn = WalletTxn::query()
|
||||
@@ -131,9 +231,6 @@ final class TicketWalletService
|
||||
$this->balanceRealtime->notifyAfterMovement($wallet, $amount, 'bet_reverse');
|
||||
}
|
||||
|
||||
/**
|
||||
* 结算派彩入账(产品文档:派彩写入钱包流水;幂等键按结算批次 + 玩家)。
|
||||
*/
|
||||
/**
|
||||
* 手动爆池补发:结算批次已派彩后,将 Jackpot 份额追加入账(幂等键按批次 + 玩家 + 爆池日志)。
|
||||
*/
|
||||
@@ -154,26 +251,7 @@ final class TicketWalletService
|
||||
}
|
||||
|
||||
$currency = strtoupper($currencyCode);
|
||||
|
||||
$wallet = PlayerWallet::query()
|
||||
->where('player_id', $player->id)
|
||||
->where('wallet_type', 'lottery')
|
||||
->where('currency_code', $currency)
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($wallet === null) {
|
||||
$wallet = PlayerWallet::query()->create([
|
||||
'player_id' => $player->id,
|
||||
'wallet_type' => 'lottery',
|
||||
'currency_code' => $currency,
|
||||
'balance' => 0,
|
||||
'frozen_balance' => 0,
|
||||
'status' => 0,
|
||||
'version' => 0,
|
||||
]);
|
||||
$wallet = PlayerWallet::query()->whereKey($wallet->id)->lockForUpdate()->firstOrFail();
|
||||
}
|
||||
$wallet = $this->lockOrCreateWallet($player, $currency);
|
||||
|
||||
$before = (int) $wallet->balance;
|
||||
$after = $before + $amountMinor;
|
||||
@@ -214,26 +292,7 @@ final class TicketWalletService
|
||||
return;
|
||||
}
|
||||
|
||||
$wallet = PlayerWallet::query()
|
||||
->where('player_id', $player->id)
|
||||
->where('wallet_type', 'lottery')
|
||||
->where('currency_code', $currency)
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($wallet === null) {
|
||||
$wallet = PlayerWallet::query()->create([
|
||||
'player_id' => $player->id,
|
||||
'wallet_type' => 'lottery',
|
||||
'currency_code' => $currency,
|
||||
'balance' => 0,
|
||||
'frozen_balance' => 0,
|
||||
'status' => 0,
|
||||
'version' => 0,
|
||||
]);
|
||||
$wallet = PlayerWallet::query()->whereKey($wallet->id)->lockForUpdate()->firstOrFail();
|
||||
}
|
||||
|
||||
$wallet = $this->lockOrCreateWallet($player, $currency);
|
||||
$before = (int) $wallet->balance;
|
||||
$after = $before + $amountMinor;
|
||||
$wallet->forceFill([
|
||||
@@ -261,6 +320,85 @@ final class TicketWalletService
|
||||
$this->balanceRealtime->notifyAfterMovement($wallet, $amountMinor, 'settle_payout');
|
||||
}
|
||||
|
||||
public function applySettlementCorrection(
|
||||
Player $player,
|
||||
string $currencyCode,
|
||||
int $amountMinor,
|
||||
string $correctionNo,
|
||||
string $remark,
|
||||
): string {
|
||||
if ($amountMinor === 0) {
|
||||
throw new TicketOperationException('adjustment_delta_zero', ErrorCode::WalletInvalidAmount->value);
|
||||
}
|
||||
|
||||
$currency = strtoupper($currencyCode);
|
||||
$wallet = $this->lockOrCreateWallet($player, $currency);
|
||||
$before = (int) $wallet->balance;
|
||||
$available = $before - (int) $wallet->frozen_balance;
|
||||
$direction = $amountMinor > 0 ? self::TXN_DIR_IN : self::TXN_DIR_OUT;
|
||||
$absAmount = abs($amountMinor);
|
||||
|
||||
if ($amountMinor < 0 && $available < $absAmount) {
|
||||
throw new TicketOperationException('bet_insufficient_balance', ErrorCode::BetInsufficientBalance->value);
|
||||
}
|
||||
|
||||
$after = $before + $amountMinor;
|
||||
$wallet->forceFill([
|
||||
'balance' => $after,
|
||||
'version' => (int) $wallet->version + 1,
|
||||
])->save();
|
||||
|
||||
$txn = WalletTxn::query()->create([
|
||||
'txn_no' => $this->newTxnNo(),
|
||||
'player_id' => $player->id,
|
||||
'wallet_id' => $wallet->id,
|
||||
'biz_type' => 'settlement_adjustment',
|
||||
'biz_no' => $correctionNo,
|
||||
'direction' => $direction,
|
||||
'amount' => $absAmount,
|
||||
'balance_before' => $before,
|
||||
'balance_after' => $after,
|
||||
'status' => self::TXN_POSTED,
|
||||
'external_ref_no' => null,
|
||||
'idempotent_key' => 'settlement_adjustment:'.$correctionNo,
|
||||
'remark' => $remark,
|
||||
]);
|
||||
|
||||
$wallet->refresh();
|
||||
$this->balanceRealtime->notifyAfterMovement($wallet, $amountMinor, $amountMinor > 0 ? 'settle_payout' : 'bet_reverse');
|
||||
|
||||
return (string) $txn->txn_no;
|
||||
}
|
||||
|
||||
private function lockOrCreateWallet(Player $player, string $currencyCode): PlayerWallet
|
||||
{
|
||||
$wallet = PlayerWallet::query()
|
||||
->where('player_id', $player->id)
|
||||
->where('wallet_type', 'lottery')
|
||||
->where('currency_code', strtoupper($currencyCode))
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($wallet === null) {
|
||||
$wallet = PlayerWallet::query()->create([
|
||||
'player_id' => $player->id,
|
||||
'wallet_type' => 'lottery',
|
||||
'currency_code' => strtoupper($currencyCode),
|
||||
'balance' => 0,
|
||||
'frozen_balance' => 0,
|
||||
'status' => 0,
|
||||
'version' => 0,
|
||||
]);
|
||||
$wallet = PlayerWallet::query()->whereKey($wallet->id)->lockForUpdate()->firstOrFail();
|
||||
}
|
||||
|
||||
if ((int) $wallet->status !== 0) {
|
||||
throw new TicketOperationException('wallet_frozen', ErrorCode::WalletLotteryFrozen->value);
|
||||
}
|
||||
|
||||
return $wallet;
|
||||
}
|
||||
|
||||
private function newTxnNo(): string
|
||||
{
|
||||
return 'WL'.now()->format('YmdHis').str_pad((string) random_int(0, 999999), 6, '0', STR_PAD_LEFT);
|
||||
|
||||
@@ -70,6 +70,21 @@ final class HttpMainSiteWalletBalanceClient
|
||||
$timeout = $config->walletTimeoutSeconds;
|
||||
$apiKey = $config->walletApiKey;
|
||||
|
||||
if (app()->environment(['production'])
|
||||
&& $config->source === \App\Services\Integration\PartnerSiteConfig::SOURCE_LEGACY_ENV
|
||||
&& (! is_string($apiKey) || trim($apiKey) === '')
|
||||
) {
|
||||
return new MainSiteWalletBalanceProbeResult(
|
||||
success: false,
|
||||
mainBalanceMinor: null,
|
||||
currencyCode: $currencyCode,
|
||||
requestUrl: '',
|
||||
httpStatus: null,
|
||||
message: 'MAIN_SITE_WALLET_API_KEY 未配置',
|
||||
responseBody: null,
|
||||
);
|
||||
}
|
||||
|
||||
$headers = ['Accept' => 'application/json'];
|
||||
if (is_string($apiKey) && $apiKey !== '') {
|
||||
$headers['Authorization'] = 'Bearer '.$apiKey;
|
||||
|
||||
@@ -53,6 +53,24 @@ final class HttpMainSiteWalletGateway implements MainSiteWalletGateway
|
||||
);
|
||||
}
|
||||
|
||||
public function refundMainForFailedLotteryDeposit(
|
||||
Player $player,
|
||||
string $currencyCode,
|
||||
int $amountMinor,
|
||||
string $idempotentKey,
|
||||
): MainSiteWalletResult {
|
||||
$config = $this->partnerSiteConfigResolver->resolveForPlayer($player);
|
||||
|
||||
return $this->post(
|
||||
$config->walletCreditPath,
|
||||
$player,
|
||||
$currencyCode,
|
||||
$amountMinor,
|
||||
$idempotentKey,
|
||||
$config,
|
||||
);
|
||||
}
|
||||
|
||||
private function post(
|
||||
string $path,
|
||||
Player $player,
|
||||
@@ -108,10 +126,6 @@ final class HttpMainSiteWalletGateway implements MainSiteWalletGateway
|
||||
);
|
||||
}
|
||||
|
||||
$url = $base.'/'.ltrim($path, '/');
|
||||
$timeout = $config->walletTimeoutSeconds;
|
||||
$apiKey = $config->walletApiKey;
|
||||
|
||||
$requestBody = [
|
||||
'site_code' => $player->site_code,
|
||||
'site_player_id' => $player->site_player_id,
|
||||
@@ -128,6 +142,22 @@ final class HttpMainSiteWalletGateway implements MainSiteWalletGateway
|
||||
],
|
||||
]);
|
||||
|
||||
$url = $base.'/'.ltrim($path, '/');
|
||||
$timeout = $config->walletTimeoutSeconds;
|
||||
$apiKey = $config->walletApiKey;
|
||||
|
||||
if (app()->environment(['production'])
|
||||
&& $config->source === \App\Services\Integration\PartnerSiteConfig::SOURCE_LEGACY_ENV
|
||||
&& (! is_string($apiKey) || trim($apiKey) === '')
|
||||
) {
|
||||
return MainSiteWalletResult::failure(
|
||||
'main_site_wallet_api_key_required',
|
||||
['reason' => 'missing_main_site_wallet_api_key'],
|
||||
false,
|
||||
$requestSnapshot,
|
||||
);
|
||||
}
|
||||
|
||||
$headers = [];
|
||||
if (is_string($apiKey) && $apiKey !== '') {
|
||||
$headers['Authorization'] = 'Bearer '.$apiKey;
|
||||
|
||||
@@ -37,7 +37,7 @@ final class LotteryTransferService
|
||||
/** PRD §12:对账后冲正 */
|
||||
private const ST_REVERSED = 'reversed';
|
||||
|
||||
/** PRD §12:对账后人工处理 */
|
||||
/** PRD §12:对账后标记结案(仅改状态,不动钱包) */
|
||||
private const ST_MANUALLY_PROCESSED = 'manually_processed';
|
||||
|
||||
private const BIZ_TRANSFER_IN = 'transfer_in';
|
||||
@@ -326,10 +326,10 @@ final class LotteryTransferService
|
||||
}
|
||||
|
||||
/**
|
||||
* 对账操作:冲正 / 人工处理。
|
||||
* 对账操作:冲正 / 补入账 / 标记结案。
|
||||
*
|
||||
* 冲正(reverse):主站确认未成功,对已扣彩票余额的转出单做反向操作(加回余额),标记为已冲正。
|
||||
* 人工处理(manually_process):管理员确认该订单已通过其它途径解决,仅标记状态,不动钱包。
|
||||
* 标记结案(manually_process):确认已在系统外处理完毕,仅改订单状态,不动钱包。
|
||||
*
|
||||
* @param 'reverse'|'manually_process' $action
|
||||
* @throws WalletOperationException
|
||||
@@ -402,6 +402,30 @@ final class LotteryTransferService
|
||||
deltaSign: 1,
|
||||
);
|
||||
}
|
||||
} elseif ($this->isEligibleForTransferInReverse($locked)) {
|
||||
$player = Player::query()->whereKey($locked->player_id)->firstOrFail();
|
||||
$refund = $this->mainSite->refundMainForFailedLotteryDeposit(
|
||||
$player,
|
||||
(string) $locked->currency_code,
|
||||
(int) $locked->amount,
|
||||
'refund:'.$locked->transfer_no,
|
||||
);
|
||||
|
||||
if (! $refund->ok) {
|
||||
throw new WalletOperationException(
|
||||
$refund->errorMessage ?? 'main_site_refund_failed',
|
||||
$refund->uncertain
|
||||
? ErrorCode::WalletTransferPending->value
|
||||
: ErrorCode::WalletExternalRejected->value,
|
||||
$refund->uncertain ? 409 : 422,
|
||||
);
|
||||
}
|
||||
|
||||
$locked->forceFill([
|
||||
'external_request_payload' => $refund->requestPayload,
|
||||
'external_response_payload' => $refund->responsePayload,
|
||||
'external_ref_no' => $refund->externalRefNo ?? $locked->external_ref_no,
|
||||
])->save();
|
||||
}
|
||||
|
||||
$locked->forceFill([
|
||||
@@ -510,6 +534,14 @@ final class LotteryTransferService
|
||||
);
|
||||
}
|
||||
|
||||
if (! $this->isEligibleForManualProcess($locked)) {
|
||||
throw new WalletOperationException(
|
||||
'manually_process_not_eligible',
|
||||
ErrorCode::WalletExternalRejected->value,
|
||||
422,
|
||||
);
|
||||
}
|
||||
|
||||
$locked->forceFill([
|
||||
'status' => self::ST_MANUALLY_PROCESSED,
|
||||
'fail_reason' => 'manually_processed: '.($remark ?: 'admin_manual'),
|
||||
@@ -518,12 +550,32 @@ final class LotteryTransferService
|
||||
}
|
||||
|
||||
/** 仅主站已扣款(有 external_ref_no)且彩票入账失败时可补完成转入。 */
|
||||
private function isEligibleForCompleteCredit(TransferOrder $order): bool
|
||||
public function isEligibleForCompleteCredit(TransferOrder $order): bool
|
||||
{
|
||||
return $order->fail_reason === 'lottery_credit_failed'
|
||||
&& trim((string) $order->external_ref_no) !== '';
|
||||
}
|
||||
|
||||
public function isEligibleForTransferInReverse(TransferOrder $order): bool
|
||||
{
|
||||
return $order->direction === self::DIR_IN
|
||||
&& $order->status === self::ST_PENDING_RECONCILE
|
||||
&& $this->isEligibleForCompleteCredit($order);
|
||||
}
|
||||
|
||||
public function isEligibleForManualProcess(TransferOrder $order): bool
|
||||
{
|
||||
if (! in_array($order->status, [self::ST_PROCESSING, self::ST_FAILED, self::ST_PENDING_RECONCILE], true)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($order->direction === self::DIR_OUT && $order->status === self::ST_PENDING_RECONCILE) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $order->fail_reason !== 'lottery_credit_failed';
|
||||
}
|
||||
|
||||
private function lockLotteryWalletById(int $playerId, string $currencyCode): PlayerWallet
|
||||
{
|
||||
$wallet = PlayerWallet::query()
|
||||
|
||||
@@ -30,4 +30,14 @@ interface MainSiteWalletGateway
|
||||
int $amountMinor,
|
||||
string $idempotentKey,
|
||||
): MainSiteWalletResult;
|
||||
|
||||
/**
|
||||
* 转入异常冲正:主站已扣款但彩票侧未入账时,把钱退回主站玩家钱包。
|
||||
*/
|
||||
public function refundMainForFailedLotteryDeposit(
|
||||
Player $player,
|
||||
string $currencyCode,
|
||||
int $amountMinor,
|
||||
string $idempotentKey,
|
||||
): MainSiteWalletResult;
|
||||
}
|
||||
|
||||
@@ -39,6 +39,21 @@ final class StubMainSiteWalletGateway implements MainSiteWalletGateway
|
||||
], $req);
|
||||
}
|
||||
|
||||
public function refundMainForFailedLotteryDeposit(
|
||||
Player $player,
|
||||
string $currencyCode,
|
||||
int $amountMinor,
|
||||
string $idempotentKey,
|
||||
): MainSiteWalletResult {
|
||||
$req = self::requestSnapshot($player, $currencyCode, $amountMinor, $idempotentKey, 'stub_refund');
|
||||
|
||||
return MainSiteWalletResult::success('stub-refund:'.$idempotentKey, [
|
||||
'stub' => true,
|
||||
'currency' => $currencyCode,
|
||||
'amount_minor' => $amountMinor,
|
||||
], $req);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user