3 Commits

Author SHA1 Message Date
0373234750 优化数据归属问题 2026-04-23 15:08:37 +08:00
378be9909d 1.优化后端管理员提现方式
2.优化后端
2026-04-23 14:11:55 +08:00
aa1299c018 1.新增获取充值/提现配置接口/api/finance/depositWithdrawConfig
2.优化充值和提现方式
2026-04-23 10:15:01 +08:00
80 changed files with 3215 additions and 959 deletions

View File

@@ -4,6 +4,7 @@ namespace app\admin\controller;
use Throwable;
use app\common\controller\Backend;
use app\common\service\ChannelSettlementService;
use support\think\Db;
use support\Response;
use Webman\Http\Request as WebmanRequest;
@@ -16,7 +17,7 @@ class Channel extends Backend
/**
* 预览接口与手动结算共用「手动结算」按钮权限(避免额外菜单节点)
*/
protected array $noNeedPermission = ['manualSettlePreview', 'channelAdminShareList', 'saveChannelAdminShare'];
protected array $noNeedPermission = ['manualSettlePreview', 'channelAdminShareList', 'saveChannelAdminShare', 'batchSettlePending', 'settleStats'];
/**
* Channel模型对象
@@ -314,7 +315,7 @@ class Channel extends Backend
return $this->error(__('You have no permission'));
}
$payload = $this->buildManualSettlePayload($row->toArray());
$payload = ChannelSettlementService::buildSettlePayload($row->toArray());
if (is_string($payload)) {
return $this->error($payload);
}
@@ -541,7 +542,7 @@ class Channel extends Backend
return $this->error('该渠道下暂无管理员,无法配置分配比例');
}
$enabledSum = '0.0000';
$enabledSum = '0.00';
$insertRows = [];
foreach ($rowsRaw as $line) {
if (!is_array($line)) {
@@ -553,12 +554,12 @@ class Channel extends Backend
}
$status = ((int) ($line['status'] ?? 1)) === 1 ? 1 : 0;
$shareRaw = $line['share_rate'] ?? null;
$shareRate = self::normalizeAmountScale($shareRaw === null ? '0' : (string) $shareRaw, 4);
if (bccomp($shareRate, '0', 4) < 0 || bccomp($shareRate, '100', 4) > 0) {
$shareRate = self::normalizeAmountScale($shareRaw === null ? '0' : (string) $shareRaw, 2);
if (bccomp($shareRate, '0', 2) < 0 || bccomp($shareRate, '100', 2) > 0) {
return $this->error('分配比例必须在0到100之间');
}
if ($status === 1) {
$enabledSum = bcadd($enabledSum, $shareRate, 4);
$enabledSum = bcadd($enabledSum, $shareRate, 2);
}
$insertRows[] = [
'channel_id' => (int) $row['id'],
@@ -572,7 +573,7 @@ class Channel extends Backend
if ($insertRows === []) {
return $this->error('请至少配置一条有效分配记录');
}
if (bccomp($enabledSum, '100.0000', 4) !== 0) {
if (bccomp($enabledSum, '100.00', 2) !== 0) {
return $this->error('启用的分配比例总和必须等于100');
}
@@ -611,63 +612,80 @@ class Channel extends Backend
return $this->error(__('You have no permission'));
}
$remark = (string) $request->post('remark', '');
$remark = trim((string) $request->post('remark', ''));
$payload = $this->buildManualSettlePayload($row->toArray());
if (is_string($payload)) {
return $this->error($payload);
}
$settlementNo = $payload['settlement_no'];
if (Db::name('agent_settlement_period')->where('settlement_no', $settlementNo)->value('id')) {
return $this->error('结算单号已存在,请稍后重试');
}
$shareRows = $this->resolveCommissionSharesForChannel((int) $row['id']);
if ($shareRows === []) {
return $this->error('渠道下无可用管理员分配比例,无法生成佣金记录');
}
$now = time();
Db::startTrans();
try {
$periodId = (int) Db::name('agent_settlement_period')->insertGetId([
'settlement_no' => $settlementNo,
'period_start_at' => $payload['period_start_ts'],
'period_end_at' => $payload['period_end_ts'],
'total_bet_amount' => $payload['total_bet_amount'],
'total_payout_amount' => $payload['total_payout_amount'],
'platform_profit_amount' => $payload['platform_profit_amount'],
'status' => 2,
'remark' => trim($remark) !== '' ? $remark : ('手动结算-渠道#' . $row['id'] . '-' . $row['name']),
'create_time' => $now,
'update_time' => $now,
]);
$commissionRows = $this->buildCommissionRowsForSplit(
$shareRows,
(int) $row['id'],
$periodId,
(string) $payload['calc_base_amount'],
(string) $payload['commission_amount'],
trim($remark) !== '' ? $remark : ('手动结算佣金-CH' . $row['id']),
$now
);
if ($commissionRows === []) {
throw new \RuntimeException('分配比例拆分失败,未生成佣金记录');
if ($this->auth->isSuperAdmin()) {
$res = ChannelSettlementService::settleBySuperAdmin((int) $row['id'], intval($this->auth->id), $remark, false);
if (($res['ok'] ?? false) !== true) {
return $this->error((string) ($res['msg'] ?? '结算失败'));
}
Db::name('agent_commission_record')->insertAll($commissionRows);
Db::name('channel')->where('id', $row['id'])->update([
'update_time' => $now,
]);
Db::commit();
} catch (Throwable $e) {
Db::rollback();
return $this->error($e->getMessage());
return $this->success('超管结算完成,渠道分红余额已入账');
}
$res = ChannelSettlementService::settleDividendByChannelAdmin((int) $row['id'], intval($this->auth->id), $remark);
if (($res['ok'] ?? false) !== true) {
return $this->error((string) ($res['msg'] ?? '结算失败'));
}
return $this->success('渠道分红已结算完成');
}
return $this->success('手动结算已完成,已生成结算周期与佣金记录');
/**
* 超管批量结算全部待结算渠道(可作为“提前结算”入口)
*/
public function batchSettlePending(WebmanRequest $request): Response
{
$response = $this->initializeBackend($request);
if ($response !== null) {
return $response;
}
if (!$this->auth->isSuperAdmin()) {
return $this->error(__('You have no permission'));
}
$res = ChannelSettlementService::settleAllDueChannels(intval($this->auth->id));
return $this->success('批量结算完成', $res);
}
/**
* 渠道结算统计卡片
*/
public function settleStats(WebmanRequest $request): Response
{
$response = $this->initializeBackend($request);
if ($response !== null) {
return $response;
}
$query = Db::name('channel');
if (!$this->auth->isSuperAdmin()) {
$query->where('id', 'in', $this->currentChannelIds ?: [0]);
}
$rows = $query->field(['id', 'status', 'carryover_balance'])->select()->toArray();
$total = count($rows);
$enabled = 0;
$disabled = 0;
$carryoverPositiveCount = 0;
$carryoverTotal = '0.00';
$carryoverPositiveTotal = '0.00';
foreach ($rows as $row) {
$status = intval($row['status'] ?? 0);
if ($status === 1) {
$enabled++;
} else {
$disabled++;
}
$carry = bcadd(strval($row['carryover_balance'] ?? '0'), '0', 2);
$carryoverTotal = bcadd($carryoverTotal, $carry, 2);
if (bccomp($carry, '0', 2) > 0) {
$carryoverPositiveCount++;
$carryoverPositiveTotal = bcadd($carryoverPositiveTotal, $carry, 2);
}
}
return $this->success('', [
'channel_total' => $total,
'enabled_count' => $enabled,
'disabled_count' => $disabled,
'carryover_positive_count' => $carryoverPositiveCount,
'carryover_total' => $carryoverTotal,
'carryover_positive_total' => $carryoverPositiveTotal,
]);
}
/**
@@ -696,7 +714,7 @@ class Channel extends Backend
$stats = $this->aggregateBetOrderForChannel($channelId, $periodStartTs, $lastEnd !== null, $endTs);
$totalBet = $stats['total_bet'];
$totalPayout = $stats['total_payout'];
$profit = bcsub($totalBet, $totalPayout, 4);
$profit = bcsub($totalBet, $totalPayout, 2);
$mode = (string) ($row['agent_mode'] ?? 'turnover');
$commission = $this->computeCommissionAmounts($row, $totalBet, $profit, $mode);
@@ -740,7 +758,7 @@ class Channel extends Backend
$base = $flag . $channelPart . $timePart;
for ($i = 0; $i < 8; $i++) {
$randPart = strtoupper(substr(bin2hex(random_bytes(4)), 0, 8));
$randPart = strtoupper(substr(bin2hex(random_bytes(4)), 0, 2));
$no = $base . $randPart;
if (!Db::name('agent_settlement_period')->where('settlement_no', $no)->value('id')) {
return $no;
@@ -784,10 +802,10 @@ class Channel extends Backend
}
$row = $query->field('SUM(total_amount) AS tb, SUM(win_amount) AS tw, SUM(jackpot_extra_amount) AS tj')->find();
$tb = $row && $row['tb'] !== null && $row['tb'] !== '' ? (string) $row['tb'] : '0.0000';
$tw = $row && $row['tw'] !== null && $row['tw'] !== '' ? (string) $row['tw'] : '0.0000';
$tj = $row && $row['tj'] !== null && $row['tj'] !== '' ? (string) $row['tj'] : '0.0000';
$totalPayout = bcadd($tw, $tj, 4);
$tb = $row && $row['tb'] !== null && $row['tb'] !== '' ? (string) $row['tb'] : '0.00';
$tw = $row && $row['tw'] !== null && $row['tw'] !== '' ? (string) $row['tw'] : '0.00';
$tj = $row && $row['tj'] !== null && $row['tj'] !== '' ? (string) $row['tj'] : '0.00';
$totalPayout = bcadd($tw, $tj, 2);
return [
'total_bet' => number_format((float) $tb, 4, '.', ''),
@@ -805,8 +823,8 @@ class Channel extends Backend
if ($ratePercent === null || $ratePercent === '') {
return '普通返水代理未配置返水分红比例';
}
$rateDec = bcdiv((string) $ratePercent, '100', 6);
$amount = bcmul($totalBet, $rateDec, 4);
$rateDec = bcdiv((string) $ratePercent, '100', 2);
$amount = bcmul($totalBet, $rateDec, 2);
return [
'commission_rate' => $rateDec,
'calc_base_amount' => $totalBet,
@@ -825,27 +843,27 @@ class Channel extends Backend
return '联营阶梯规则无效或为空';
}
if (bccomp($platformProfit, '0', 4) <= 0) {
if (bccomp($platformProfit, '0', 2) <= 0) {
return [
'commission_rate' => '0.000000',
'calc_base_amount' => '0.0000',
'commission_amount' => '0.0000',
'commission_rate' => '0.00',
'calc_base_amount' => '0.00',
'commission_amount' => '0.00',
];
}
$afterFee = bcmul($platformProfit, bcsub('1', (string) $fee, 8), 4);
if (bccomp($afterFee, '0', 4) <= 0) {
$afterFee = bcmul($platformProfit, bcsub('1', (string) $fee, 2), 2);
if (bccomp($afterFee, '0', 2) <= 0) {
return [
'commission_rate' => '0.000000',
'calc_base_amount' => '0.0000',
'commission_amount' => '0.0000',
'commission_rate' => '0.00',
'calc_base_amount' => '0.00',
'commission_amount' => '0.00',
];
}
$playerLoss = $platformProfit;
$share = $this->pickAffiliateShareRateFromLadder($rules, $playerLoss);
$rateDec = number_format($share, 6, '.', '');
$amount = bcmul($afterFee, $rateDec, 4);
$amount = bcmul($afterFee, $rateDec, 2);
return [
'commission_rate' => $rateDec,
@@ -888,7 +906,7 @@ class Channel extends Backend
];
}
usort($out, function ($a, $b) {
return bccomp($a['minLoss'], $b['minLoss'], 4);
return bccomp($a['minLoss'], $b['minLoss'], 2);
});
return $out;
}
@@ -900,7 +918,7 @@ class Channel extends Backend
{
$chosen = (float) $rules[0]['shareRate'];
foreach ($rules as $rule) {
if (bccomp($playerLoss, $rule['minLoss'], 4) >= 0) {
if (bccomp($playerLoss, $rule['minLoss'], 2) >= 0) {
$chosen = (float) $rule['shareRate'];
}
}
@@ -959,24 +977,24 @@ class Channel extends Backend
->select()
->toArray();
if ($rows !== []) {
$sum = '0.0000';
$sum = '0.00';
$out = [];
foreach ($rows as $row) {
$adminId = (int) ($row['admin_id'] ?? 0);
if ($adminId <= 0) {
continue;
}
$shareRate = self::normalizeAmountScale((string) ($row['share_rate'] ?? '0'), 4);
if (bccomp($shareRate, '0', 4) <= 0) {
$shareRate = self::normalizeAmountScale((string) ($row['share_rate'] ?? '0'), 2);
if (bccomp($shareRate, '0', 2) <= 0) {
continue;
}
$sum = bcadd($sum, $shareRate, 4);
$sum = bcadd($sum, $shareRate, 2);
$out[] = [
'admin_id' => $adminId,
'share_rate' => $shareRate,
];
}
if ($out !== [] && bccomp($sum, '100.0000', 4) === 0) {
if ($out !== [] && bccomp($sum, '100.00', 2) === 0) {
return $out;
}
}
@@ -987,7 +1005,7 @@ class Channel extends Backend
}
return [[
'admin_id' => (int) $fallbackAdminId,
'share_rate' => '100.0000',
'share_rate' => '100.00',
]];
}
@@ -1007,19 +1025,19 @@ class Channel extends Backend
if ($shareRows === []) {
return [];
}
$sum = '0.0000';
$sum = '0.00';
$rows = [];
$lastIndex = count($shareRows) - 1;
foreach ($shareRows as $index => $shareRow) {
$shareRate = self::normalizeAmountScale((string) ($shareRow['share_rate'] ?? '0'), 4);
$shareDec = bcdiv($shareRate, '100', 8);
$shareRate = self::normalizeAmountScale((string) ($shareRow['share_rate'] ?? '0'), 2);
$shareDec = bcdiv($shareRate, '100', 2);
$amount = $index === $lastIndex
? bcsub($commissionTotal, $sum, 4)
: bcmul($commissionTotal, $shareDec, 4);
? bcsub($commissionTotal, $sum, 2)
: bcmul($commissionTotal, $shareDec, 2);
if ($index !== $lastIndex) {
$sum = bcadd($sum, $amount, 4);
$sum = bcadd($sum, $amount, 2);
}
$effectiveRate = bccomp($calcBaseAmount, '0', 4) <= 0 ? '0.000000' : bcdiv($amount, $calcBaseAmount, 6);
$effectiveRate = bccomp($calcBaseAmount, '0', 2) <= 0 ? '0.00' : bcdiv($amount, $calcBaseAmount, 2);
$rows[] = [
'settlement_period_id' => $periodId,
'channel_id' => $channelId,
@@ -1052,17 +1070,17 @@ class Channel extends Backend
}
$adminNames = Db::name('admin')->where('id', 'in', $adminIds)->column('username', 'id');
$sum = '0.0000';
$sum = '0.00';
$out = [];
$lastIndex = count($shareRows) - 1;
foreach ($shareRows as $index => $shareRow) {
$shareRate = self::normalizeAmountScale((string) ($shareRow['share_rate'] ?? '0'), 4);
$shareDec = bcdiv($shareRate, '100', 8);
$shareRate = self::normalizeAmountScale((string) ($shareRow['share_rate'] ?? '0'), 2);
$shareDec = bcdiv($shareRate, '100', 2);
$amount = $index === $lastIndex
? bcsub($commissionTotal, $sum, 4)
: bcmul($commissionTotal, $shareDec, 4);
? bcsub($commissionTotal, $sum, 2)
: bcmul($commissionTotal, $shareDec, 2);
if ($index !== $lastIndex) {
$sum = bcadd($sum, $amount, 4);
$sum = bcadd($sum, $amount, 2);
}
$adminId = (int) ($shareRow['admin_id'] ?? 0);
$out[] = [

View File

@@ -21,16 +21,16 @@ class Dashboard extends Backend
return $response;
}
$scope = $this->channelScopeOrNull();
$ownerAdminId = $this->ownerAdminIdOrNull();
$todayStart = strtotime(date('Y-m-d'));
$todayEnd = $todayStart + 86400 - 1;
$yesterdayStart = $todayStart - 86400;
$yesterdayEnd = $todayStart - 1;
$userTotal = $this->countUsers($scope);
$newToday = $this->countUsersInRange($scope, $todayStart, $todayEnd);
$newYesterday = $this->countUsersInRange($scope, $yesterdayStart, $yesterdayEnd);
$userTotal = $this->countUsers($ownerAdminId);
$newToday = $this->countUsersInRange($ownerAdminId, $todayStart, $todayEnd);
$newYesterday = $this->countUsersInRange($ownerAdminId, $yesterdayStart, $yesterdayEnd);
$growthPct = null;
if ($newYesterday > 0) {
$growthPct = round(($newToday - $newYesterday) / $newYesterday * 100, 1);
@@ -38,14 +38,14 @@ class Dashboard extends Backend
$growthPct = 100.0;
}
$depositAgg = $this->aggregateDepositToday($scope, $todayStart, $todayEnd);
$withdrawPending = $this->countWithdrawPending($scope);
$betAgg = $this->aggregateBetToday($scope, $todayStart, $todayEnd);
$depositAgg = $this->aggregateDepositToday($ownerAdminId, $todayStart, $todayEnd);
$withdrawPending = $this->countWithdrawPending($ownerAdminId);
$betAgg = $this->aggregateBetToday($ownerAdminId, $todayStart, $todayEnd);
$trend = $this->buildSevenDayTrend($scope);
$channelShare = $this->buildChannelShare($scope);
$depositAmountChannelShare = $this->buildDepositAmountChannelShare($scope);
$recentUsers = $this->fetchRecentUsers($scope, 10);
$trend = $this->buildSevenDayTrend($ownerAdminId);
$channelShare = $this->buildChannelShare($ownerAdminId);
$depositAmountChannelShare = $this->buildDepositAmountChannelShare($ownerAdminId);
$recentUsers = $this->fetchRecentUsers($ownerAdminId, 10);
return $this->success('', [
'remark' => get_route_remark(),
@@ -68,27 +68,27 @@ class Dashboard extends Backend
}
/**
* @param int[]|null $scope null=超管不限制;非 null 时 whereIn channel_id
* @param int|null $ownerAdminId null=超管不限制;非 null 时 where admin_id
*/
private function countUsers(?array $scope): int
private function countUsers(?int $ownerAdminId): int
{
$q = Db::name('user');
if ($scope !== null) {
$q->whereIn('channel_id', $scope);
if ($ownerAdminId !== null) {
$q->where('admin_id', '=', $ownerAdminId);
}
return intval($q->count());
}
/**
* @param int[]|null $scope
* @param int|null $ownerAdminId
*/
private function countUsersInRange(?array $scope, int $start, int $end): int
private function countUsersInRange(?int $ownerAdminId, int $start, int $end): int
{
$q = Db::name('user')
->where('create_time', '>=', $start)
->where('create_time', '<=', $end);
if ($scope !== null) {
$q->whereIn('channel_id', $scope);
if ($ownerAdminId !== null) {
$q->where('admin_id', '=', $ownerAdminId);
}
return intval($q->count());
}
@@ -96,19 +96,19 @@ class Dashboard extends Backend
/**
* 今日成功充值status=1按创建日落在今日与 mock 即时成功一致)。
*
* @param int[]|null $scope
* @param int|null $ownerAdminId
* @return array{count:int, amount:string}
*/
private function aggregateDepositToday(?array $scope, int $todayStart, int $todayEnd): array
private function aggregateDepositToday(?int $ownerAdminId, int $todayStart, int $todayEnd): array
{
$q = Db::name('deposit_order')
->where('status', 1)
->where('create_time', '>=', $todayStart)
->where('create_time', '<=', $todayEnd);
if ($scope !== null) {
$q->whereIn('channel_id', $scope);
if ($ownerAdminId !== null) {
$q->whereIn('user_id', $this->scopedUserIds($ownerAdminId));
}
$rows = $q->fieldRaw('COUNT(*) AS c, COALESCE(SUM(CAST(amount AS DECIMAL(18,4))),0) AS s')->find();
$rows = $q->fieldRaw('COUNT(*) AS c, COALESCE(SUM(CAST(amount AS DECIMAL(18,2))),0) AS s')->find();
if (!is_array($rows)) {
$rows = [];
}
@@ -120,13 +120,13 @@ class Dashboard extends Backend
}
/**
* @param int[]|null $scope
* @param int|null $ownerAdminId
*/
private function countWithdrawPending(?array $scope): int
private function countWithdrawPending(?int $ownerAdminId): int
{
$q = Db::name('withdraw_order')->where('status', 0);
if ($scope !== null) {
$q->whereIn('channel_id', $scope);
if ($ownerAdminId !== null) {
$q->whereIn('user_id', $this->scopedUserIds($ownerAdminId));
}
return intval($q->count());
}
@@ -134,19 +134,19 @@ class Dashboard extends Backend
/**
* 今日投注创建时间在今日且订单未作废status 1 或 2
*
* @param int[]|null $scope
* @param int|null $ownerAdminId
* @return array{count:int, amount:string}
*/
private function aggregateBetToday(?array $scope, int $todayStart, int $todayEnd): array
private function aggregateBetToday(?int $ownerAdminId, int $todayStart, int $todayEnd): array
{
$q = Db::name('bet_order')
->whereIn('status', [1, 2])
->where('create_time', '>=', $todayStart)
->where('create_time', '<=', $todayEnd);
if ($scope !== null) {
$q->whereIn('channel_id', $scope);
if ($ownerAdminId !== null) {
$q->whereIn('user_id', $this->scopedUserIds($ownerAdminId));
}
$rows = $q->fieldRaw('COUNT(*) AS c, COALESCE(SUM(CAST(total_amount AS DECIMAL(18,4))),0) AS s')->find();
$rows = $q->fieldRaw('COUNT(*) AS c, COALESCE(SUM(CAST(total_amount AS DECIMAL(18,2))),0) AS s')->find();
if (!is_array($rows)) {
$rows = [];
}
@@ -157,10 +157,10 @@ class Dashboard extends Backend
}
/**
* @param int[]|null $scope
* @param int|null $ownerAdminId
* @return array{days:string[], new_users:int[], deposit_amount:string[], bet_amount:string[]}
*/
private function buildSevenDayTrend(?array $scope): array
private function buildSevenDayTrend(?int $ownerAdminId): array
{
$days = [];
$newUsers = [];
@@ -172,16 +172,16 @@ class Dashboard extends Backend
$dayEnd = $dayStart + 86400 - 1;
$days[] = date('m-d', $dayStart);
$newUsers[] = $this->countUsersInRange($scope, $dayStart, $dayEnd);
$newUsers[] = $this->countUsersInRange($ownerAdminId, $dayStart, $dayEnd);
$dq = Db::name('deposit_order')
->where('status', 1)
->where('create_time', '>=', $dayStart)
->where('create_time', '<=', $dayEnd);
if ($scope !== null) {
$dq->whereIn('channel_id', $scope);
if ($ownerAdminId !== null) {
$dq->whereIn('user_id', $this->scopedUserIds($ownerAdminId));
}
$drow = $dq->fieldRaw('COALESCE(SUM(CAST(amount AS DECIMAL(18,4))),0) AS s')->find();
$drow = $dq->fieldRaw('COALESCE(SUM(CAST(amount AS DECIMAL(18,2))),0) AS s')->find();
$dsum = is_array($drow) && isset($drow['s']) ? strval($drow['s']) : '0';
$depositAmounts[] = $this->formatMoney2($dsum);
@@ -189,10 +189,10 @@ class Dashboard extends Backend
->whereIn('status', [1, 2])
->where('create_time', '>=', $dayStart)
->where('create_time', '<=', $dayEnd);
if ($scope !== null) {
$bq->whereIn('channel_id', $scope);
if ($ownerAdminId !== null) {
$bq->whereIn('user_id', $this->scopedUserIds($ownerAdminId));
}
$brow = $bq->fieldRaw('COALESCE(SUM(CAST(total_amount AS DECIMAL(18,4))),0) AS s')->find();
$brow = $bq->fieldRaw('COALESCE(SUM(CAST(total_amount AS DECIMAL(18,2))),0) AS s')->find();
$bsum = is_array($brow) && isset($brow['s']) ? strval($brow['s']) : '0';
$betAmounts[] = $this->formatMoney2($bsum);
}
@@ -208,14 +208,14 @@ class Dashboard extends Backend
/**
* 用户按渠道分布(取前 8 名,其余合并为「其他」)。
*
* @param int[]|null $scope
* @param int|null $ownerAdminId
* @return list<array{name:string, value:int}>
*/
private function buildChannelShare(?array $scope): array
private function buildChannelShare(?int $ownerAdminId): array
{
$q = Db::name('user')->fieldRaw('channel_id, COUNT(*) AS c')->group('channel_id');
if ($scope !== null) {
$q->whereIn('channel_id', $scope);
if ($ownerAdminId !== null) {
$q->where('admin_id', '=', $ownerAdminId);
}
$rows = $q->orderRaw('c DESC')->select()->toArray();
if ($rows === []) {
@@ -257,17 +257,17 @@ class Dashboard extends Backend
/**
* 成功充值金额按订单归属渠道汇总status=1受渠道范围限制
*
* @param int[]|null $scope
* @param int|null $ownerAdminId
* @return list<array{name:string, value:string}> value 为两位小数字符串,供前端饼图展示
*/
private function buildDepositAmountChannelShare(?array $scope): array
private function buildDepositAmountChannelShare(?int $ownerAdminId): array
{
$q = Db::name('deposit_order')
->where('status', 1)
->fieldRaw('channel_id, COALESCE(SUM(CAST(amount AS DECIMAL(18,4))),0) AS s')
->fieldRaw('channel_id, COALESCE(SUM(CAST(amount AS DECIMAL(18,2))),0) AS s')
->group('channel_id');
if ($scope !== null) {
$q->whereIn('channel_id', $scope);
if ($ownerAdminId !== null) {
$q->whereIn('user_id', $this->scopedUserIds($ownerAdminId));
}
$rows = $q->select()->toArray();
if ($rows === []) {
@@ -308,7 +308,7 @@ class Dashboard extends Backend
$rest = array_slice($list, 8);
$other = '0';
foreach ($rest as $item) {
$other = bcadd($other, $item['value'], 4);
$other = bcadd($other, $item['value'], 2);
}
$otherFormatted = $this->formatMoney2($other);
if (bccomp($otherFormatted, '0', 2) > 0) {
@@ -322,17 +322,17 @@ class Dashboard extends Backend
}
/**
* @param int[]|null $scope
* @param int|null $ownerAdminId
* @return list<array{id:int, username:string, create_time:int, channel_name:string, head_image:string}>
*/
private function fetchRecentUsers(?array $scope, int $limit): array
private function fetchRecentUsers(?int $ownerAdminId, int $limit): array
{
$q = Db::name('user')
->field(['id', 'username', 'create_time', 'channel_id', 'head_image'])
->order('id', 'desc')
->limit($limit);
if ($scope !== null) {
$q->whereIn('channel_id', $scope);
if ($ownerAdminId !== null) {
$q->where('admin_id', '=', $ownerAdminId);
}
$rows = $q->select()->toArray();
if ($rows === []) {
@@ -366,28 +366,37 @@ class Dashboard extends Backend
if (!is_numeric($amount)) {
return '0.00';
}
$normalized = bcadd($amount, '0', 4);
$normalized = bcadd($amount, '0', 2);
return bcadd($normalized, '0', 2);
}
/**
* 非超管:按管理员所属渠道过滤;未绑定渠道时按 channel_id IN (0) 与列表页一致
* 超管:返回 null表示 SQL 不加渠道条件。
* 非超管:按当前管理员名下用户过滤
* 超管:返回 null表示 SQL 不加管理员条件。
*
* @return int[]|null
* @return int|null
*/
private function channelScopeOrNull(): ?array
private function ownerAdminIdOrNull(): ?int
{
if (!$this->auth || $this->auth->isSuperAdmin()) {
return null;
}
$admin = Db::name('admin')->field(['id', 'channel_id'])->where('id', $this->auth->id)->find();
$ids = [];
if ($admin && !empty($admin['channel_id'])) {
$ids[] = $admin['channel_id'];
$idRaw = $this->auth->id;
if ($idRaw === null || $idRaw === '' || !is_numeric(strval($idRaw))) {
return 0;
}
$id = intval(strval($idRaw));
return $id > 0 ? $id : 0;
}
return $ids !== [] ? array_values(array_unique($ids)) : [0];
/**
* @return int[]
*/
private function scopedUserIds(int $ownerAdminId): array
{
$ids = Db::name('user')->where('admin_id', '=', $ownerAdminId)->column('id');
$ids = array_map('intval', $ids);
return $ids === [] ? [0] : array_values(array_unique($ids));
}
}

View File

@@ -251,9 +251,27 @@ class Rule extends Backend
->select()
->toArray();
foreach ($rules as $idx => $rule) {
$title = $rule['title'] ?? '';
if (is_string($title) && $title !== '') {
$rules[$idx]['title'] = $this->menuTitleToZh($title);
}
}
return $this->assembleTree ? $this->tree->assembleChild($rules) : $rules;
}
private function menuTitleToZh(string $title): string
{
static $zhMap = null;
if (!is_array($zhMap)) {
$mapFile = app_path() . '/common/lang/zh-cn/admin_rule_title.php';
$loaded = is_file($mapFile) ? include $mapFile : [];
$zhMap = is_array($loaded) ? $loaded : [];
}
return isset($zhMap[$title]) && is_string($zhMap[$title]) ? $zhMap[$title] : $title;
}
private function autoAssignPermission(int $id, int $pid): void
{
$groups = AdminGroup::where('rules', '<>', '*')->select();

View File

@@ -4,7 +4,6 @@ namespace app\admin\controller\config;
use app\common\controller\Backend;
use app\common\library\game\DepositChannel as DepositChannelLib;
use app\common\library\game\DepositTier as DepositTierLib;
use app\common\library\game\FinanceCashierConfig as FinanceCashierConfigLib;
use app\common\service\GameHotDataCoordinator;
use app\common\service\GameHotDataLock;
@@ -56,7 +55,7 @@ class DepositChannel extends Backend
}
/**
* 列表baTablelist / total / remark+ registry + tier_options弹窗用
* 列表baTablelist / total / remark+ registry(弹窗展示名
*/
public function index(WebmanRequest $request): Response
{
@@ -71,7 +70,6 @@ class DepositChannel extends Backend
return $this->error(__('Parameter error'));
}
$tierOptions = $this->buildTierOptions();
$registryOut = $this->buildRegistryOut();
$parsed = DepositChannelLib::parseStoredOverridesFromDb();
@@ -136,7 +134,6 @@ class DepositChannel extends Backend
'total' => $total,
'remark' => '',
'registry' => $registryOut,
'tier_options' => $tierOptions,
'items' => $pageRows,
]);
}
@@ -308,32 +305,6 @@ class DepositChannel extends Backend
}
}
/**
* @return list<array{id: string, label: string}>
*/
private function buildTierOptions(): array
{
$tierRow = Db::name('game_config')->where('config_key', DepositTierLib::CONFIG_KEY)->find();
$allTiers = DepositTierLib::parseFromConfigValue($tierRow['config_value'] ?? null);
$tierOptions = [];
foreach ($allTiers as $t) {
if (!is_array($t)) {
continue;
}
$tid = isset($t['id']) && is_string($t['id']) ? $t['id'] : '';
if ($tid === '') {
continue;
}
$title = isset($t['title']) && is_string($t['title']) ? trim($t['title']) : '';
$tierOptions[] = [
'id' => $tid,
'label' => $title !== '' ? $title . ' (' . $tid . ')' : $tid,
];
}
return $tierOptions;
}
/**
* @return array<string, array{name: string, name_en: string, sort: int}>
*/
@@ -376,12 +347,6 @@ class DepositChannel extends Backend
} else {
$form['status'] = $current['status'] ?? 0;
}
if (array_key_exists('tier_ids', $payload) && is_array($payload['tier_ids'])) {
$form['tier_ids'] = $payload['tier_ids'];
} else {
$form['tier_ids'] = isset($current['tier_ids']) && is_array($current['tier_ids']) ? $current['tier_ids'] : [];
}
return $this->normalizeChannelFormRow($form, $code);
}
@@ -398,24 +363,11 @@ class DepositChannel extends Backend
if ($st === true || $st === 1 || $st === '1') {
$status = 1;
}
$tierIds = [];
if (isset($payload['tier_ids']) && is_array($payload['tier_ids'])) {
foreach ($payload['tier_ids'] as $tid) {
if (is_string($tid)) {
$t = trim($tid);
if ($t !== '' && preg_match('/^[a-zA-Z0-9_\-]{1,32}$/', $t)) {
$tierIds[] = $t;
}
}
}
$tierIds = array_values(array_unique($tierIds));
}
return [
'code' => $code,
'sort' => $sort,
'status' => $status,
'tier_ids' => $tierIds,
'tier_ids' => [],
];
}
}

View File

@@ -3,6 +3,7 @@
namespace app\admin\controller\config;
use app\common\controller\Backend;
use app\common\library\game\FinanceCashierConfig as FinanceCashierConfigLib;
use app\common\library\game\DepositTier as DepositTierLib;
use app\common\service\GameHotDataCoordinator;
use app\common\service\GameHotDataLock;
@@ -21,6 +22,45 @@ class DepositTier extends Backend
protected array $noNeedPermission = ['index', 'save'];
/**
* 读取支付货币下拉来源game_config.finance_cashier.currencies
* 用于充值档位表单的“支付货币”选项,避免前端硬编码。
*/
public function currencyOptions(WebmanRequest $request): Response
{
$response = $this->initializeBackend($request);
if ($response !== null) {
return $response;
}
if (!$this->hasNodePermission($request, 'index')) {
return $this->error(__('You have no permission'), [], 401);
}
if ($request->method() !== 'GET') {
return $this->error(__('Parameter error'));
}
$row = Db::name('game_config')->where('config_key', FinanceCashierConfigLib::CONFIG_KEY)->find();
$cfg = FinanceCashierConfigLib::parseFromConfigValue($row['config_value'] ?? null);
$currencies = [];
if (isset($cfg['currencies']) && is_array($cfg['currencies'])) {
foreach ($cfg['currencies'] as $item) {
if (!is_array($item)) {
continue;
}
$code = isset($item['code']) && is_string($item['code']) ? strtoupper(trim($item['code'])) : '';
if ($code === '') {
continue;
}
$currencies[] = $code;
}
}
$currencies = array_values(array_unique($currencies));
if ($currencies === []) {
$currencies = ['MYR', 'CNY', 'USD', 'USDT', 'VND', 'THB', 'SGD', 'IDR'];
}
return $this->success('', ['list' => $currencies]);
}
private function hasNodePermission(WebmanRequest $request, string $action): bool
{
if (!$this->auth) {

View File

@@ -6,7 +6,6 @@ namespace app\admin\controller\config;
use app\common\controller\Backend;
use app\common\library\game\DepositChannel as DepositChannelLib;
use app\common\library\game\DepositTier as DepositTierLib;
use app\common\library\game\FinanceCashierConfig as FinanceCashierConfigLib;
use app\common\service\GameHotDataCoordinator;
use app\common\service\GameHotDataLock;
@@ -91,7 +90,6 @@ class FinanceCashierConfig extends Backend
return $this->success('', [
'form' => $form,
'registry' => $this->buildRegistryOut(),
'tier_options' => $this->buildTierOptions(),
]);
}
@@ -176,32 +174,6 @@ class FinanceCashierConfig extends Backend
}
}
/**
* @return list<array{id: string, label: string}>
*/
private function buildTierOptions(): array
{
$tierRow = Db::name('game_config')->where('config_key', DepositTierLib::CONFIG_KEY)->find();
$allTiers = DepositTierLib::parseFromConfigValue(is_array($tierRow) ? ($tierRow['config_value'] ?? null) : null);
$tierOptions = [];
foreach ($allTiers as $t) {
if (!is_array($t)) {
continue;
}
$tid = isset($t['id']) && is_string($t['id']) ? $t['id'] : '';
if ($tid === '') {
continue;
}
$title = isset($t['title']) && is_string($t['title']) ? trim($t['title']) : '';
$tierOptions[] = [
'id' => $tid,
'label' => $title !== '' ? $title . ' (' . $tid . ')' : $tid,
];
}
return $tierOptions;
}
/**
* @return array<string, array{name: string, name_en: string, sort: int}>
*/

View File

@@ -32,4 +32,53 @@ class UserNoticeRead extends Backend
$this->model = new \app\common\model\UserNoticeRead();
return null;
}
protected function _index(): Response
{
if ($this->request && $this->request->get('select')) {
return $this->select($this->request);
}
list($where, $alias, $limit, $order) = $this->queryBuilder();
$table = strtolower($this->model->getTable());
$mainShort = $alias[$table] ?? '';
if ($mainShort !== '' && $this->auth && !$this->auth->isSuperAdmin()) {
$where[] = ['user.admin_id', 'in', $this->scopedAdminIds()];
}
$res = $this->model
->withJoin($this->withJoinTable, $this->withJoinType)
->with($this->withJoinTable)
->alias($alias)
->where($where)
->order($order)
->paginate($limit);
return $this->success('', [
'list' => $res->items(),
'total' => $res->total(),
'remark' => get_route_remark(),
]);
}
/**
* 当前管理员可见的管理员ID集合本人 + 下级角色组内管理员)
*
* @return int[]
*/
private function scopedAdminIds(): array
{
if (!$this->auth) {
return [0];
}
if ($this->auth->isSuperAdmin()) {
return [];
}
$groupIds = $this->auth->getAdminChildGroups();
$adminIds = $groupIds ? $this->auth->getGroupAdmins($groupIds) : [];
$adminIds[] = $this->auth->id;
$adminIds = array_map(static fn($id) => intval(strval($id)), $adminIds);
$adminIds = array_values(array_unique(array_filter($adminIds, static fn($id) => $id > 0)));
return $adminIds === [] ? [0] : $adminIds;
}
}

View File

@@ -0,0 +1,268 @@
<?php
namespace app\admin\controller\order;
use app\common\controller\Backend;
use app\common\service\AdminWalletService;
use support\think\Db;
use support\Response;
use Throwable;
use Webman\Http\Request as WebmanRequest;
/**
* 管理员提现记录(审核)
*/
class AdminWithdrawOrder extends Backend
{
protected array $noNeedPermission = ['stats'];
protected ?object $model = null;
protected bool $modelValidate = false;
protected string|array $quickSearchField = ['id', 'order_no', 'receive_account', 'remark'];
protected string|array $defaultSortField = ['id' => 'desc'];
protected string|array $orderGuarantee = ['id' => 'desc'];
protected array $withJoinTable = ['admin', 'channel', 'reviewAdmin'];
protected function initController(WebmanRequest $request): ?Response
{
$this->model = new \app\common\model\AdminWithdrawOrder();
return null;
}
protected function _index(): Response
{
if ($this->request && $this->request->get('select')) {
return $this->select($this->request);
}
list($where, $alias, $limit, $order) = $this->queryBuilder();
$table = strtolower($this->model->getTable());
$mainShort = $alias[$table] ?? '';
if ($mainShort !== '' && $this->auth && !$this->auth->isSuperAdmin()) {
$where[] = [$mainShort . '.channel_id', 'in', $this->getCurrentAdminTopChannelIds()];
}
$res = $this->model
->withJoin($this->withJoinTable, $this->withJoinType)
->with($this->withJoinTable)
->visible([
'admin' => ['username'],
'channel' => ['name'],
'reviewAdmin' => ['username'],
])
->alias($alias)
->where($where)
->order($order)
->paginate($limit);
return $this->success('', [
'list' => $res->items(),
'total' => $res->total(),
'remark' => get_route_remark(),
]);
}
protected function _edit(): Response
{
$pk = $this->model->getPk();
$id = $this->request ? ($this->request->post($pk) ?? $this->request->get($pk)) : null;
if ($id === null || $id === '') {
return $this->error(__('Parameter error'));
}
if ($this->request && $this->request->method() === 'POST') {
return $this->error('请使用通过/拒绝按钮审核');
}
$row = $this->loadWithRelations(intval(strval($id)));
if (!$row) {
return $this->error(__('Record not found'));
}
if (!$this->canReviewOrder($row)) {
return $this->error(__('You have no permission'));
}
return $this->success('', ['row' => $row]);
}
public function approve(WebmanRequest $request): Response
{
$response = $this->initializeBackend($request);
if ($response !== null) {
return $response;
}
if ($request->method() !== 'POST') {
return $this->error(__('Parameter error'));
}
$id = intval(strval($request->post('id', 0)));
if ($id <= 0) {
return $this->error(__('Parameter error'));
}
$order = Db::name('admin_withdraw_order')->where('id', $id)->find();
if (!is_array($order)) {
return $this->error(__('Record not found'));
}
if (!$this->canReviewOrder($order)) {
return $this->error(__('You have no permission'));
}
if (intval($order['status'] ?? 0) !== 0) {
return $this->error('该提现订单已审核');
}
$remark = trim((string) $request->post('remark', ''));
Db::startTrans();
try {
AdminWalletService::approveWithdraw($order, intval($this->auth->id), $remark);
Db::commit();
} catch (Throwable $e) {
Db::rollback();
return $this->error($e->getMessage());
}
return $this->success('审核通过');
}
public function reject(WebmanRequest $request): Response
{
$response = $this->initializeBackend($request);
if ($response !== null) {
return $response;
}
if ($request->method() !== 'POST') {
return $this->error(__('Parameter error'));
}
$id = intval(strval($request->post('id', 0)));
if ($id <= 0) {
return $this->error(__('Parameter error'));
}
$remark = trim((string) $request->post('remark', ''));
if ($remark === '') {
return $this->error('请填写拒绝原因');
}
$order = Db::name('admin_withdraw_order')->where('id', $id)->find();
if (!is_array($order)) {
return $this->error(__('Record not found'));
}
if (!$this->canReviewOrder($order)) {
return $this->error(__('You have no permission'));
}
if (intval($order['status'] ?? 0) !== 0) {
return $this->error('该提现订单已审核');
}
Db::startTrans();
try {
AdminWalletService::rejectWithdraw($order, intval($this->auth->id), $remark);
Db::commit();
} catch (Throwable $e) {
Db::rollback();
return $this->error($e->getMessage());
}
return $this->success('审核拒绝完成');
}
public function stats(WebmanRequest $request): Response
{
$response = $this->initializeBackend($request);
if ($response !== null) {
return $response;
}
$query = Db::name('admin_withdraw_order');
if ($this->auth && !$this->auth->isSuperAdmin()) {
$query->where('channel_id', 'in', $this->getCurrentAdminTopChannelIds());
}
$rows = $query->field(['status', 'amount', 'actual_amount'])->select()->toArray();
$total = count($rows);
$pending = 0;
$approved = 0;
$rejected = 0;
$totalAmount = '0.00';
$pendingAmount = '0.00';
$approvedAmount = '0.00';
foreach ($rows as $row) {
$status = intval($row['status'] ?? 0);
$amount = bcadd(strval($row['amount'] ?? '0'), '0', 2);
$actual = bcadd(strval($row['actual_amount'] ?? '0'), '0', 2);
$totalAmount = bcadd($totalAmount, $amount, 2);
if ($status === 0) {
$pending++;
$pendingAmount = bcadd($pendingAmount, $amount, 2);
} elseif ($status === 1) {
$approved++;
$approvedAmount = bcadd($approvedAmount, $actual, 2);
} elseif ($status === 2) {
$rejected++;
}
}
return $this->success('', [
'total_count' => $total,
'pending_count' => $pending,
'approved_count' => $approved,
'rejected_count' => $rejected,
'total_amount' => $totalAmount,
'pending_amount' => $pendingAmount,
'approved_amount' => $approvedAmount,
]);
}
private function loadWithRelations(int $id): ?array
{
$row = $this->model
->withJoin($this->withJoinTable, $this->withJoinType)
->with($this->withJoinTable)
->visible([
'admin' => ['username'],
'channel' => ['name'],
'reviewAdmin' => ['username'],
])
->where($this->model->getTable() . '.id', $id)
->find();
return $row ? $row->toArray() : null;
}
private function canReviewOrder(array $order): bool
{
if (!$this->auth) {
return false;
}
if ($this->auth->isSuperAdmin()) {
return true;
}
$channelId = intval($order['channel_id'] ?? 0);
if ($channelId <= 0) {
return false;
}
$allowed = $this->getCurrentAdminTopChannelIds();
return in_array($channelId, $allowed, true);
}
/**
* 当前管理员可审核的“顶级角色组(pid=0)”所属渠道
*
* @return int[]
*/
private function getCurrentAdminTopChannelIds(): array
{
$uid = intval($this->auth->id ?? 0);
if ($uid <= 0) {
return [0];
}
$groupIds = Db::name('admin_group_access')->where('uid', $uid)->column('group_id');
if ($groupIds === []) {
return [0];
}
$rows = Db::name('admin_group')
->field(['id', 'pid', 'channel_id'])
->where('id', 'in', $groupIds)
->where('pid', 0)
->whereNotNull('channel_id')
->select()
->toArray();
$channelIds = [];
foreach ($rows as $row) {
$cid = intval($row['channel_id'] ?? 0);
if ($cid > 0) {
$channelIds[] = $cid;
}
}
return $channelIds === [] ? [0] : array_values(array_unique($channelIds));
}
}

View File

@@ -3,7 +3,6 @@
namespace app\admin\controller\order;
use app\common\controller\Backend;
use support\think\Db;
use support\Response;
use Webman\Http\Request as WebmanRequest;
@@ -79,8 +78,7 @@ class BetOrder extends Backend
$table = strtolower($this->model->getTable());
$mainShort = $alias[$table] ?? '';
if ($mainShort !== '' && $this->auth && !$this->auth->isSuperAdmin()) {
$channelIds = $this->getScopedChannelIdsForFilter();
$where[] = [$mainShort . '.channel_id', 'in', $channelIds !== [] ? $channelIds : [0]];
$where[] = ['user.admin_id', 'in', $this->scopedAdminIds()];
}
$res = $this->model
@@ -104,9 +102,11 @@ class BetOrder extends Backend
}
/**
* 当前管理员可见的管理员ID集合本人 + 下级角色组内管理员)
*
* @return int[]
*/
private function getScopedChannelIdsForFilter(): array
private function scopedAdminIds(): array
{
if (!$this->auth) {
return [0];
@@ -114,14 +114,12 @@ class BetOrder extends Backend
if ($this->auth->isSuperAdmin()) {
return [];
}
$admin = Db::name('admin')
->field(['id', 'channel_id'])
->where('id', $this->auth->id)
->find();
$ids = [];
if ($admin && !empty($admin['channel_id'])) {
$ids[] = $admin['channel_id'];
}
return array_values(array_unique($ids));
$groupIds = $this->auth->getAdminChildGroups();
$adminIds = $groupIds ? $this->auth->getGroupAdmins($groupIds) : [];
$adminIds[] = $this->auth->id;
$adminIds = array_map(static fn($id) => intval(strval($id)), $adminIds);
$adminIds = array_values(array_unique(array_filter($adminIds, static fn($id) => $id > 0)));
return $adminIds === [] ? [0] : $adminIds;
}
}

View File

@@ -1,29 +0,0 @@
<?php
namespace app\admin\controller\order;
use app\common\library\game\DepositChannel;
/**
* 渠道充值订单仅列出已注册且启用的支付渠道pay_channel产生的充值单
*/
class DepositChannelOrder extends DepositOrder
{
/**
* @param list<array<mixed>> $where
*/
protected function appendDepositOrderIndexWhere(array &$where, string $mainShort): void
{
if ($mainShort === '') {
return;
}
$effective = DepositChannel::effectiveRowsFromDb();
$codes = DepositChannel::enabledPayChannelCodes($effective);
if ($codes === []) {
$where[] = [$mainShort . '.pay_channel', '=', '__no_pay_channel__'];
return;
}
$where[] = [$mainShort . '.pay_channel', 'in', $codes];
}
}

View File

@@ -3,7 +3,6 @@
namespace app\admin\controller\order;
use app\common\controller\Backend;
use support\think\Db;
use support\Response;
use Webman\Http\Request as WebmanRequest;
@@ -49,8 +48,7 @@ class DepositOrder extends Backend
$table = strtolower($this->model->getTable());
$mainShort = $alias[$table] ?? '';
if ($mainShort !== '' && $this->auth && !$this->auth->isSuperAdmin()) {
$channelIds = $this->getScopedChannelIdsForFilter();
$where[] = [$mainShort . '.channel_id', 'in', $channelIds !== [] ? $channelIds : [0]];
$where[] = ['user.admin_id', 'in', $this->scopedAdminIds()];
}
$this->appendDepositOrderIndexWhere($where, $mainShort);
@@ -115,7 +113,7 @@ class DepositOrder extends Backend
->withJoin($this->withJoinTable, $this->withJoinType)
->with($this->withJoinTable)
->visible([
'user' => ['username', 'phone'],
'user' => ['username', 'phone', 'admin_id'],
'channel' => ['name'],
])
->where($this->model->getTable() . '.id', $id)
@@ -131,24 +129,26 @@ class DepositOrder extends Backend
if (!$this->auth || $this->auth->isSuperAdmin()) {
return true;
}
$channelIds = $this->getScopedChannelIdsForFilter();
if ($channelIds === []) {
$userRow = $row['user'] ?? null;
if (!is_array($userRow)) {
return false;
}
$raw = $row['channel_id'] ?? null;
if ($raw === null || $raw === '') {
$adminIdRaw = $userRow['admin_id'] ?? null;
if ($adminIdRaw === null || $adminIdRaw === '') {
return false;
}
if (!is_numeric(strval($raw))) {
if (!is_numeric(strval($adminIdRaw))) {
return false;
}
return in_array(intval(strval($raw)), $channelIds, true);
return in_array(intval(strval($adminIdRaw)), $this->scopedAdminIds(), true);
}
/**
* 当前管理员可见的管理员ID集合本人 + 下级角色组内管理员)
*
* @return int[]
*/
private function getScopedChannelIdsForFilter(): array
private function scopedAdminIds(): array
{
if (!$this->auth) {
return [0];
@@ -156,11 +156,12 @@ class DepositOrder extends Backend
if ($this->auth->isSuperAdmin()) {
return [];
}
$admin = Db::name('admin')->field(['id', 'channel_id'])->where('id', $this->auth->id)->find();
$ids = [];
if ($admin && !empty($admin['channel_id'])) {
$ids[] = $admin['channel_id'];
}
return array_values(array_unique($ids));
$groupIds = $this->auth->getAdminChildGroups();
$adminIds = $groupIds ? $this->auth->getGroupAdmins($groupIds) : [];
$adminIds[] = $this->auth->id;
$adminIds = array_map(static fn($id) => intval(strval($id)), $adminIds);
$adminIds = array_values(array_unique(array_filter($adminIds, static fn($id) => $id > 0)));
return $adminIds === [] ? [0] : $adminIds;
}
}

View File

@@ -24,7 +24,7 @@ class WithdrawOrder extends Backend
protected bool $modelSceneValidate = true;
protected string|array $quickSearchField = ['id', 'order_no', 'remark'];
protected string|array $quickSearchField = ['id', 'order_no', 'idempotency_key', 'receive_type', 'receive_account', 'remark'];
protected string|array $defaultSortField = ['id' => 'desc'];
@@ -48,8 +48,7 @@ class WithdrawOrder extends Backend
$table = strtolower($this->model->getTable());
$mainShort = $alias[$table] ?? '';
if ($mainShort !== '' && $this->auth && !$this->auth->isSuperAdmin()) {
$channelIds = $this->getScopedChannelIdsForFilter();
$where[] = [$mainShort . '.channel_id', 'in', $channelIds !== [] ? $channelIds : [0]];
$where[] = ['user.admin_id', 'in', $this->scopedAdminIds()];
}
$res = $this->model
@@ -119,16 +118,16 @@ class WithdrawOrder extends Backend
$newAmount = $this->decimalParam($request->post('amount'), '0');
$newFee = $this->decimalParam($request->post('fee'), '0');
if (bccomp($newAmount, '0', 4) <= 0) {
if (bccomp($newAmount, '0', 2) <= 0) {
return $this->error('申请金额必须大于 0');
}
if (bccomp($newFee, '0', 4) < 0) {
if (bccomp($newFee, '0', 2) < 0) {
return $this->error('手续费不能为负');
}
if (bccomp($newFee, $newAmount, 4) > 0) {
if (bccomp($newFee, $newAmount, 2) > 0) {
return $this->error('手续费不能大于申请金额');
}
$newActual = bcsub($newAmount, $newFee, 4);
$newActual = bcsub($newAmount, $newFee, 2);
$remarkRaw = $request->post('remark');
$remark = is_string($remarkRaw) ? trim($remarkRaw) : '';
@@ -149,8 +148,8 @@ class WithdrawOrder extends Backend
if ($userId <= 0) {
return $this->error('订单缺少用户信息');
}
$oldAmount = bcadd(strval($order['amount'] ?? '0'), '0', 4);
$diff = bcsub($newAmount, $oldAmount, 4);
$oldAmount = bcadd(strval($order['amount'] ?? '0'), '0', 2);
$diff = bcsub($newAmount, $oldAmount, 2);
$now = time();
$adminId = $this->intParam($this->auth->id ?? 0);
@@ -168,7 +167,7 @@ class WithdrawOrder extends Backend
Db::startTrans();
try {
// 金额调整差额处理
$cmp = bccomp($diff, '0', 4);
$cmp = bccomp($diff, '0', 2);
if ($cmp > 0) {
// 新金额更大:再冻结用户 diff
$userRow = Db::name('user')->where('id', $userId)->find();
@@ -176,12 +175,12 @@ class WithdrawOrder extends Backend
Db::rollback();
return $this->error('关联用户不存在');
}
$beforeCoin = bcadd(strval($userRow['coin'] ?? '0'), '0', 4);
if (bccomp($beforeCoin, $diff, 4) < 0) {
$beforeCoin = bcadd(strval($userRow['coin'] ?? '0'), '0', 2);
if (bccomp($beforeCoin, $diff, 2) < 0) {
Db::rollback();
return $this->error('用户余额不足以补扣调整差额');
}
$afterCoin = bcsub($beforeCoin, $diff, 4);
$afterCoin = bcsub($beforeCoin, $diff, 2);
Db::name('user')->where('id', $userId)->update([
'coin' => $afterCoin,
'total_withdraw_coin' => Db::raw('total_withdraw_coin + ' . $diff),
@@ -205,14 +204,14 @@ class WithdrawOrder extends Backend
]);
} elseif ($cmp < 0) {
// 新金额更小:退回差额
$abs = bcsub('0', $diff, 4);
$abs = bcsub('0', $diff, 2);
$userRow = Db::name('user')->where('id', $userId)->find();
if (!$userRow) {
Db::rollback();
return $this->error('关联用户不存在');
}
$beforeCoin = bcadd(strval($userRow['coin'] ?? '0'), '0', 4);
$afterCoin = bcadd($beforeCoin, $abs, 4);
$beforeCoin = bcadd(strval($userRow['coin'] ?? '0'), '0', 2);
$afterCoin = bcadd($beforeCoin, $abs, 2);
Db::name('user')->where('id', $userId)->update([
'coin' => $afterCoin,
'total_withdraw_coin' => Db::raw('total_withdraw_coin - ' . $abs),
@@ -301,7 +300,7 @@ class WithdrawOrder extends Backend
if ($userId <= 0) {
return $this->error('订单缺少用户信息');
}
$amount = bcadd(strval($order['amount'] ?? '0'), '0', 4);
$amount = bcadd(strval($order['amount'] ?? '0'), '0', 2);
$channelIdRaw = $order['channel_id'] ?? null;
$channelId = ($channelIdRaw === null || $channelIdRaw === '')
? null
@@ -318,8 +317,8 @@ class WithdrawOrder extends Backend
Db::rollback();
return $this->error('关联用户不存在');
}
$beforeCoin = bcadd(strval($userRow['coin'] ?? '0'), '0', 4);
$afterCoin = bcadd($beforeCoin, $amount, 4);
$beforeCoin = bcadd(strval($userRow['coin'] ?? '0'), '0', 2);
$afterCoin = bcadd($beforeCoin, $amount, 2);
Db::name('user')->where('id', $userId)->update([
'coin' => $afterCoin,
'total_withdraw_coin' => Db::raw('total_withdraw_coin - ' . $amount),
@@ -386,17 +385,17 @@ class WithdrawOrder extends Backend
if (!$this->auth || $this->auth->isSuperAdmin()) {
return true;
}
$channelIds = $this->getScopedChannelIdsForFilter();
if ($channelIds === []) {
$uidRaw = is_array($row) ? ($row['user_id'] ?? null) : ($row->user_id ?? null);
$uid = $this->intParam($uidRaw);
if ($uid <= 0) {
return false;
}
$raw = is_array($row) ? ($row['channel_id'] ?? null) : ($row->channel_id ?? null);
if ($raw === null || $raw === '') {
// 无归属渠道的数据只有超管可见
$user = Db::name('user')->field(['id', 'admin_id'])->where('id', $uid)->find();
if (!is_array($user)) {
return false;
}
$cid = $this->intParam($raw);
return in_array($cid, $channelIds, true);
$ownerAdminId = $this->intParam($user['admin_id'] ?? 0);
return $ownerAdminId > 0 && in_array($ownerAdminId, $this->scopedAdminIds(), true);
}
private function intParam($raw): int
@@ -413,9 +412,9 @@ class WithdrawOrder extends Backend
private function decimalParam($raw, string $default): string
{
if ($raw === null || $raw === '' || !is_numeric(strval($raw))) {
return bcadd($default, '0', 4);
return bcadd($default, '0', 2);
}
return bcadd(strval($raw), '0', 4);
return bcadd(strval($raw), '0', 2);
}
private function adminDisplayName(): string
@@ -432,14 +431,35 @@ class WithdrawOrder extends Backend
}
/**
* 把 4 位小数金额压缩成最多 2 位小数用于展示(不影响落库精度
* 当前管理员可见的管理员ID集合本人 + 下级角色组内管理员
*
* @return int[]
*/
private function scopedAdminIds(): array
{
if (!$this->auth) {
return [0];
}
if ($this->auth->isSuperAdmin()) {
return [];
}
$groupIds = $this->auth->getAdminChildGroups();
$adminIds = $groupIds ? $this->auth->getGroupAdmins($groupIds) : [];
$adminIds[] = $this->auth->id;
$adminIds = array_map(fn($id) => $this->intParam($id), $adminIds);
$adminIds = array_values(array_unique(array_filter($adminIds, fn($id) => $id > 0)));
return $adminIds === [] ? [0] : $adminIds;
}
/**
* 把 2 位小数金额压缩成最多 2 位小数用于展示(不影响落库精度)
*/
private function shortAmount(string $amount): string
{
if (!is_numeric($amount)) {
return $amount;
}
$normalized = bcadd($amount, '0', 4);
$normalized = bcadd($amount, '0', 2);
$negative = false;
if (str_starts_with($normalized, '-')) {
$negative = true;
@@ -453,22 +473,4 @@ class WithdrawOrder extends Backend
return $negative ? ('-' . $v) : $v;
}
/**
* @return int[]
*/
private function getScopedChannelIdsForFilter(): array
{
if (!$this->auth) {
return [0];
}
if ($this->auth->isSuperAdmin()) {
return [];
}
$admin = Db::name('admin')->field(['id', 'channel_id'])->where('id', $this->auth->id)->find();
$ids = [];
if ($admin && !empty($admin['channel_id'])) {
$ids[] = $admin['channel_id'];
}
return array_values(array_unique($ids));
}
}

View File

@@ -5,12 +5,17 @@ declare(strict_types=1);
namespace app\admin\controller\routine;
use app\admin\model\Admin;
use app\common\service\AdminWalletService;
use app\common\controller\Backend;
use support\think\Db;
use Webman\Http\Request;
use support\Response;
use Throwable;
class AdminInfo extends Backend
{
protected array $noNeedPermission = ['walletSummary', 'walletRecords', 'withdrawApply'];
protected ?object $model = null;
protected array|string $preExcludeFields = ['username', 'last_login_time', 'password', 'salt', 'status'];
@@ -88,4 +93,109 @@ class AdminInfo extends Backend
return $this->success('', ['row' => $row]);
}
public function walletSummary(Request $request): Response
{
$response = $this->initializeBackend($request);
if ($response !== null) {
return $response;
}
$adminId = intval($this->auth->id ?? 0);
if ($adminId <= 0) {
return $this->error(__('Parameter error'));
}
$wallet = AdminWalletService::ensureWallet($adminId);
return $this->success('', [
'wallet' => [
'balance' => strval($wallet['balance'] ?? '0.00'),
'frozen_balance' => strval($wallet['frozen_balance'] ?? '0.00'),
'total_income' => strval($wallet['total_income'] ?? '0.00'),
'total_withdraw' => strval($wallet['total_withdraw'] ?? '0.00'),
],
]);
}
public function walletRecords(Request $request): Response
{
$response = $this->initializeBackend($request);
if ($response !== null) {
return $response;
}
$adminId = intval($this->auth->id ?? 0);
if ($adminId <= 0) {
return $this->error(__('Parameter error'));
}
$limit = intval((string) $request->get('limit', 10));
if ($limit <= 0) {
$limit = 10;
}
$res = Db::name('admin_wallet_record')->alias('awr')
->leftJoin('channel c', 'awr.channel_id = c.id')
->leftJoin('admin oa', 'awr.operator_admin_id = oa.id')
->field([
'awr.id', 'awr.biz_type', 'awr.direction', 'awr.amount', 'awr.balance_before', 'awr.balance_after',
'awr.ref_type', 'awr.ref_id', 'awr.remark', 'awr.create_time', 'c.name as channel_name', 'oa.username as operator_admin_username',
])
->where('awr.admin_id', $adminId)
->order('awr.id', 'desc')
->paginate($limit);
return $this->success('', [
'list' => $res->items(),
'total' => $res->total(),
]);
}
public function withdrawApply(Request $request): Response
{
$response = $this->initializeBackend($request);
if ($response !== null) {
return $response;
}
if ($request->method() !== 'POST') {
return $this->error(__('Parameter error'));
}
$adminId = intval($this->auth->id ?? 0);
if ($adminId <= 0) {
return $this->error(__('Parameter error'));
}
$withdrawCoinRaw = $request->post('withdraw_coin', '');
$withdrawCoin = is_string($withdrawCoinRaw) ? trim($withdrawCoinRaw) : (is_numeric($withdrawCoinRaw) ? strval($withdrawCoinRaw) : '');
$receiveAccount = trim(is_string($request->post('receive_account', '')) ? $request->post('receive_account', '') : '');
$receiveType = trim(is_string($request->post('receive_type', '')) ? $request->post('receive_type', '') : '');
$idempotencyKey = trim(is_string($request->post('idempotency_key', '')) ? $request->post('idempotency_key', '') : '');
if ($withdrawCoin === '' || $receiveAccount === '' || $receiveType === '' || $idempotencyKey === '') {
return $this->error('参数缺失');
}
if (mb_strlen($idempotencyKey) > 64) {
return $this->error('幂等键过长');
}
if (!is_numeric($withdrawCoin) || bccomp($withdrawCoin, '0', 2) <= 0) {
return $this->error('提现金额必须大于0');
}
$withdrawCoin = bcadd($withdrawCoin, '0', 2);
$allowedReceiveTypes = ['bank', 'ewallet', 'crypto'];
if (!in_array($receiveType, $allowedReceiveTypes, true)) {
return $this->error('收款类型不合法,仅支持 bank/ewallet/crypto');
}
$remark = trim((string) $request->post('remark', ''));
$admin = Db::name('admin')->field(['id', 'channel_id'])->where('id', $adminId)->find();
$channelId = is_array($admin) ? intval($admin['channel_id'] ?? 0) : 0;
Db::startTrans();
try {
$res = AdminWalletService::applyWithdraw($adminId, $channelId, $withdrawCoin, $receiveType, $receiveAccount, $idempotencyKey, $remark);
if (($res['ok'] ?? false) !== true) {
Db::rollback();
return $this->error(strval($res['msg'] ?? '提现申请失败'));
}
Db::commit();
} catch (Throwable $e) {
Db::rollback();
return $this->error($e->getMessage());
}
return $this->success('提现申请已提交,待渠道超管审核', [
'order_id' => intval($res['order_id'] ?? 0),
'order_no' => strval($res['order_no'] ?? ''),
'idempotent_hit' => !empty($res['idempotent_hit']),
]);
}
}

View File

@@ -15,6 +15,11 @@ use Webman\Http\Request as WebmanRequest;
*/
class User extends Backend
{
/**
* 这些接口只要求登录,不单独校验权限节点
*/
protected array $noNeedPermission = ['adminScopeTree'];
/**
* User模型对象
* @var object|null
@@ -22,6 +27,11 @@ class User extends Backend
*/
protected ?object $model = null;
/**
* 渠道管理员仅可管理自己名下admin_id=当前管理员)的用户
*/
protected bool|string|int $dataLimit = true;
protected array|string $preExcludeFields = ['id', 'uuid', 'create_time', 'update_time', 'invite_code', 'coin', 'total_deposit_coin', 'total_withdraw_coin', 'bet_flow_coin'];
protected array $withJoinTable = ['channel', 'admin'];
@@ -232,7 +242,7 @@ class User extends Backend
if ($amountText === '' || !is_numeric($amountText)) {
return $this->error('金额格式不正确');
}
if (bccomp($amountText, '0', 4) <= 0) {
if (bccomp($amountText, '0', 2) <= 0) {
return $this->error('金额必须大于0');
}
@@ -267,16 +277,16 @@ class User extends Backend
}
$before = strval($user['coin'] ?? '0');
$delta = self::normalizeAmountScale($amountText, 4);
$delta = self::normalizeAmountScale($amountText, 2);
if ($op === 'credit') {
$after = bcadd($before, $delta, 4);
$after = bcadd($before, $delta, 2);
$bizType = 'admin_credit';
$direction = 1;
} else {
if (bccomp($before, $delta, 4) < 0) {
if (bccomp($before, $delta, 2) < 0) {
return $this->error('余额不足,扣点失败');
}
$after = bcsub($before, $delta, 4);
$after = bcsub($before, $delta, 2);
$bizType = 'admin_deduct';
$direction = 2;
}
@@ -365,7 +375,7 @@ class User extends Backend
private static function formatAmountForDisplay(string $amount): string
{
$normalized = self::normalizeAmountScale($amount, 4);
$normalized = self::normalizeAmountScale($amount, 2);
$negative = false;
if (str_starts_with($normalized, '-')) {
$negative = true;
@@ -390,9 +400,17 @@ class User extends Backend
return $response;
}
$currentAdminLeaf = $this->getCurrentAdminLeaf();
if ($currentAdminLeaf === null) {
return $this->error(__('Record not found'));
}
$groupIds = $this->getManageableAdminGroupIds();
if ($groupIds === []) {
return $this->success('', ['list' => []]);
return $this->success('', [
'list' => [$currentAdminLeaf],
'current_admin_id' => $currentAdminLeaf['value'],
]);
}
$groups = Db::name('admin_group')
@@ -488,12 +506,45 @@ class User extends Backend
foreach ($roots as $rid) {
$tree[] = $buildNode($rid);
}
if (!isset($adminPrimary[intval(strval($currentAdminLeaf['value']))])) {
$tree[] = $currentAdminLeaf;
}
return $this->success('', [
'list' => $tree,
'current_admin_id' => $currentAdminLeaf['value'],
]);
}
private function getCurrentAdminLeaf(): ?array
{
$adminIdRaw = $this->auth->id ?? null;
if ($adminIdRaw === null || $adminIdRaw === '' || !is_numeric(strval($adminIdRaw))) {
return null;
}
$adminId = intval(strval($adminIdRaw));
if ($adminId <= 0) {
return null;
}
$row = Db::name('admin')
->field(['id', 'username', 'channel_id', 'invite_code'])
->where('id', $adminId)
->find();
if (!$row) {
return null;
}
$invite = $row['invite_code'] ?? '';
$invite = is_string($invite) ? $invite : '';
$channelId = $row['channel_id'] ?? null;
return [
'value' => strval($adminId),
'label' => strval($row['username'] ?? ('#' . strval($adminId))),
'is_leaf' => true,
'channel_id' => $channelId === null || $channelId === '' ? null : intval(strval($channelId)),
'invite_code' => $invite,
];
}
/**
* @return int[]
*/

View File

@@ -3,7 +3,6 @@
namespace app\admin\controller\user;
use app\common\controller\Backend;
use support\think\Db;
use support\Response;
use Webman\Http\Request as WebmanRequest;
@@ -79,8 +78,7 @@ class UserWalletRecord extends Backend
$table = strtolower($this->model->getTable());
$mainShort = $alias[$table] ?? '';
if ($mainShort !== '' && $this->auth && !$this->auth->isSuperAdmin()) {
$channelIds = $this->getScopedChannelIdsForFilter();
$where[] = [$mainShort . '.channel_id', 'in', $channelIds !== [] ? $channelIds : [0]];
$where[] = ['user.admin_id', 'in', $this->scopedAdminIds()];
}
$res = $this->model
@@ -104,11 +102,11 @@ class UserWalletRecord extends Backend
}
/**
* 非超管:与渠道管理一致,仅本账号相关渠道
* 当前管理员可见的管理员ID集合本人 + 下级角色组内管理员)
*
* @return int[]
*/
private function getScopedChannelIdsForFilter(): array
private function scopedAdminIds(): array
{
if (!$this->auth) {
return [0];
@@ -116,14 +114,12 @@ class UserWalletRecord extends Backend
if ($this->auth->isSuperAdmin()) {
return [];
}
$admin = Db::name('admin')
->field(['id', 'channel_id'])
->where('id', $this->auth->id)
->find();
$ids = [];
if ($admin && !empty($admin['channel_id'])) {
$ids[] = $admin['channel_id'];
}
return array_values(array_unique($ids));
$groupIds = $this->auth->getAdminChildGroups();
$adminIds = $groupIds ? $this->auth->getGroupAdmins($groupIds) : [];
$adminIds[] = $this->auth->id;
$adminIds = array_map(static fn($id) => intval(strval($id)), $adminIds);
$adminIds = array_values(array_unique(array_filter($adminIds, static fn($id) => $id > 0)));
return $adminIds === [] ? [0] : $adminIds;
}
}

View File

@@ -278,35 +278,41 @@ class Auth extends \ba\Auth
public function getMenus(int $uid = 0): array
{
$menus = parent::getMenus($uid ?: $this->id);
// 库内 title 为中文;仅英文界面走 __()。若对 zh-cn 也 __()Symfony 在找不到键时会 fallback 到 en
// 命中 admin_rule_title 后会把中文标题误译成英文。
$localeNorm = str_replace('_', '-', strtolower(locale()));
$toEnglish = ($localeNorm === 'en');
return $this->translateMenuRuleTitles($menus, $toEnglish);
return $this->translateMenuRuleTitles($menus);
}
/**
* 将 admin_rule.title 在英文界面译为英文;中文界面保持库内原文
* 英文映射见 app/common/lang/en/admin_rule_title.php
* 菜单标题统一按中文显示(不随语言切换)
* 若 title 为英文动作名/英文菜单名,按中文映射表转换。
*
* @param array<int, array<string, mixed>> $menus
* @return array<int, array<string, mixed>>
*/
private function translateMenuRuleTitles(array $menus, bool $toEnglish): array
private function translateMenuRuleTitles(array $menus): array
{
foreach ($menus as $k => $item) {
if (isset($item['title']) && is_string($item['title']) && $item['title'] !== '') {
$menus[$k]['title'] = $toEnglish ? __($item['title']) : $item['title'];
$menus[$k]['title'] = $this->menuTitleToZh($item['title']);
}
if (!empty($item['children']) && is_array($item['children'])) {
$menus[$k]['children'] = $this->translateMenuRuleTitles($item['children'], $toEnglish);
$menus[$k]['children'] = $this->translateMenuRuleTitles($item['children']);
}
}
return $menus;
}
private function menuTitleToZh(string $title): string
{
static $zhMap = null;
if (!is_array($zhMap)) {
$mapFile = app_path() . '/common/lang/zh-cn/admin_rule_title.php';
$loaded = is_file($mapFile) ? include $mapFile : [];
$zhMap = is_array($loaded) ? $loaded : [];
}
return isset($zhMap[$title]) && is_string($zhMap[$title]) ? $zhMap[$title] : $title;
}
public function isSuperAdmin(): bool
{
return in_array('*', $this->getRuleIds());

View File

@@ -77,20 +77,20 @@ class Account extends Frontend
'create_time' => $user->create_time ?? 0,
// 资金字段4 位小数字符串,与 /api/wallet/balanceSummary 对齐)
'coin' => $coinBalance,
'coin_balance' => $coinBalance,
'frozen_balance' => '0.0000',
'total_deposit_coin' => WithdrawFlow::amountString($user->total_deposit_coin ?? '0'),
'total_withdraw_coin' => WithdrawFlow::amountString($user->total_withdraw_coin ?? '0'),
'bet_flow_coin' => $flow['bet_flow_coin'],
'max_withdrawable' => $maxWithdrawable,
'coin' => floatval($coinBalance),
'coin_balance' => floatval($coinBalance),
'frozen_balance' => 0.00,
'total_deposit_coin' => floatval(WithdrawFlow::amountString($user->total_deposit_coin ?? '0')),
'total_withdraw_coin' => floatval(WithdrawFlow::amountString($user->total_withdraw_coin ?? '0')),
'bet_flow_coin' => floatval($flow['bet_flow_coin']),
'max_withdrawable' => floatval($maxWithdrawable),
'withdraw_flow' => [
'ratio' => $flow['ratio'],
'net_deposit' => $flow['net_deposit'],
'required_bet_flow' => $flow['required_bet_flow'],
'remaining_bet_flow' => $flow['remaining_bet_flow'],
'ratio' => floatval($flow['ratio']),
'net_deposit' => floatval($flow['net_deposit']),
'required_bet_flow' => floatval($flow['required_bet_flow']),
'remaining_bet_flow' => floatval($flow['remaining_bet_flow']),
'eligible' => $flow['eligible'],
'max_withdraw_by_flow' => $flow['flow_unlimited'] ? null : $flow['max_withdraw_by_flow'],
'max_withdraw_by_flow' => $flow['flow_unlimited'] ? null : floatval($flow['max_withdraw_by_flow']),
'flow_unlimited' => $flow['flow_unlimited'],
'pending_withdraw' => [
'count' => $pendingWithdrawCount,

View File

@@ -62,6 +62,10 @@ class Auth extends MobileBase
return $this->mobileError(2002, 'Invite code not bound to channel');
}
$extend['channel_id'] = (int) $channelId;
$channelStatus = Db::name('channel')->where('id', (int) $channelId)->value('status');
if (intval($channelStatus) !== 1) {
return $this->mobileError(2002, 'Channel disabled');
}
$registered = $this->auth->register($username, $password, $phone, $email, 1, $extend);
if (!$registered) {
@@ -140,7 +144,7 @@ class Auth extends MobileBase
'user' => [
'username' => $userInfo['username'] ?? '',
'uuid' => $userInfo['uuid'] ?? '',
'coin' => $userInfo['coin'] ?? '0.0000',
'coin' => $userInfo['coin'] ?? '0.00',
'channel_id' => $userInfo['channel_id'] ?? null,
'risk_flags' => $userInfo['risk_flags'] ?? 0,
],

View File

@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace app\api\controller;
use app\common\library\finance\DepositMockGateway;
use app\common\library\finance\DepositSettlement;
use app\common\library\finance\WithdrawFlow;
use app\common\library\game\DepositChannel as DepositChannelLib;
@@ -12,13 +13,26 @@ use app\common\library\game\FinanceCashierConfig as FinanceCashierConfigLib;
use app\common\model\DepositOrder;
use app\common\model\GameConfig;
use app\common\model\WithdrawOrder;
use app\common\service\DepositOrderExpireService;
use app\common\service\UserPushService;
use support\Response;
use support\think\Db;
use Throwable;
use Webman\Http\Request;
use function response;
class Finance extends MobileBase
{
/**
* 模拟第三方收银台页与支付回调,无需 user-token仅 HMAC 防篡改。
*/
protected array $noNeedLogin = ['depositMockPayPage', 'depositMockNotify'];
/**
* 允许浏览器直接打开 pay_url 而不带 auth-token。
*/
protected array $noNeedAuthToken = ['depositMockPayPage', 'depositMockNotify'];
/**
* 充值档位列表(仅启用档位,按 sort 升序)
*/
@@ -36,7 +50,7 @@ class Finance extends MobileBase
foreach ($tiers as $tier) {
$amount = $this->amountString($tier['amount'] ?? '0');
$bonus = $this->amountString($tier['bonus_amount'] ?? '0');
$total = bcadd($amount, $bonus, 4);
$total = bcadd($amount, $bonus, 2);
$payAmount = $this->amountString($tier['pay_amount'] ?? '0');
$currency = isset($tier['currency']) && is_string($tier['currency']) ? strtoupper(trim($tier['currency'])) : 'CNY';
if ($currency === '') {
@@ -49,10 +63,10 @@ class Finance extends MobileBase
'tier_key' => $tierId,
'title' => $localized['title'],
'currency' => $currency,
'pay_amount' => $payAmount,
'amount' => $amount,
'bonus_amount' => $bonus,
'total_amount' => $total,
'pay_amount' => $this->amountNumber($payAmount),
'amount' => $this->amountNumber($amount),
'bonus_amount' => $this->amountNumber($bonus),
'total_amount' => $this->amountNumber($total),
'desc' => $localized['desc'],
'channels' => DepositChannelLib::channelsForTier($tierId, $effectiveChannels, $lang),
];
@@ -77,15 +91,18 @@ class Finance extends MobileBase
/**
* 创建充值订单
*
* 当前为 mock 支付网关,点击即成功:服务端直接在同一请求内完成订单入账
* 未来接入真实第三方支付时,仅需把 "立即结算" 替换为 "返回 pay_url 进入网关"
* 并把入账动作放到网关回调里完成(回调中调用 DepositSettlement::settle
* 当前为 mock 支付网关:本接口仅创建待支付订单并返回 pay_url
* 未来接入真实第三方支付时,仅需替换 pay_url 生成与回调验签,入账仍在回调中调用 DepositSettlement::settle。
*
* 请求application/json 或 x-www-form-urlencoded
* - tier_id / tier_key: 必填,档位唯一标识(与 depositTierList 中 id、tier_key 一致)
* - channel_code: 必填,支付渠道代码(与 depositTierList 各档位 channels[].code 一致)
* - idempotency_key: 必填,客户端幂等键,短时间内重复提交只生成一次订单
*
* 流程:仅创建 `status=0` 的待支付订单,返回 `pay_url`(含签名的模拟「第三方收银台」页);玩家打开后点确认,
* 由服务端 `depositMockNotify` 模拟网关联调完成入账。未来接入真实三方时,将「打开 pay_url + 等回调」替换为
* 真网关,入账仍走 `DepositSettlement::settle`。
*
* 响应(统一结构,未来接入第三方也保持此形状):
* - order_no / amount / pay_channel / paid / pay_url / status / create_time / pay_time
*/
@@ -119,20 +136,33 @@ class Finance extends MobileBase
return $this->mobileError(2004, 'Pay channel not available');
}
// 幂等命中:直接返回已有订单
$user = $this->auth->getUser();
$userId = intval(strval($user->id));
// 先做超时清理,再做幂等命中与“最多三笔待支付”限制
DepositOrderExpireService::expirePendingOrders($userId, null);
// 幂等命中:直接返回已有订单(允许客户端重试拿回同一 pay_url
try {
$existing = DepositOrder::where('idempotency_key', $idempotencyKey)->find();
if ($existing) {
if (intval($existing->user_id) !== intval($this->auth->id)) {
return $this->mobileError(1002, 'Idempotency key conflict');
}
return $this->mobileSuccess($this->buildDepositResponse($existing));
return $this->mobileSuccess($this->buildDepositResponse($existing, $this->publicOriginFromRequest($request)));
}
} catch (Throwable $e) {
// 忽略幂等查询失败,继续创建
}
$user = $this->auth->getUser();
$pendingCount = DepositOrderExpireService::pendingCountByUserId($userId);
if ($pendingCount >= DepositOrderExpireService::MAX_PENDING_DEPOSIT) {
return $this->mobileError(2005, 'Too many pending deposit orders', [
'max_pending' => DepositOrderExpireService::MAX_PENDING_DEPOSIT,
'pending_count' => $pendingCount,
'expire_seconds' => DepositOrderExpireService::EXPIRE_SECONDS,
]);
}
$orderNo = 'DP' . date('YmdHis') . substr(str_replace('.', '', uniqid('', true)), -6);
$curSnap = isset($tier['currency']) && is_string($tier['currency']) ? strtoupper(trim($tier['currency'])) : 'CNY';
if ($curSnap === '') {
@@ -157,7 +187,6 @@ class Finance extends MobileBase
$channelId = intval(strval($user->channel_id));
}
$orderId = 0;
try {
$order = DepositOrder::create([
'order_no' => $orderNo,
@@ -169,70 +198,207 @@ class Finance extends MobileBase
'status' => 0,
'pay_channel' => $channelCode,
'deposit_tier_id' => $tier['id'],
'proof_image' => '',
'pay_account_snapshot' => json_encode($tierSnapshot, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
'remark' => '',
'create_time' => $now,
'update_time' => $now,
]);
$orderId = intval($order->id);
} catch (Throwable $e) {
$msg = $e->getMessage();
if (stripos($msg, 'Duplicate') !== false && stripos($msg, 'uk_deposit_order_idem') !== false) {
$existing = DepositOrder::where('idempotency_key', $idempotencyKey)->find();
if ($existing) {
return $this->mobileSuccess($this->buildDepositResponse($existing));
return $this->mobileSuccess($this->buildDepositResponse($existing, $this->publicOriginFromRequest($request)));
}
}
return $this->mobileError(2000, $msg);
}
// Mock 网关:立即结算,入账到钱包
try {
DepositSettlement::settle(
$orderId,
DepositSettlement::SOURCE_MOCK_GATEWAY,
'mock gateway auto settled',
null,
'channel_code=' . $channelCode
);
} catch (Throwable $e) {
return $this->mobileError(2000, $e->getMessage());
}
$settled = DepositOrder::where('id', $orderId)->find();
if (!$settled) {
return $this->mobileError(2000, 'Order not found after settle');
}
return $this->mobileSuccess($this->buildDepositResponse($settled));
// 仅落待支付单;真实入账在模拟网关联调 depositMockNotify 中完成
return $this->mobileSuccess($this->buildDepositResponse($order, $this->publicOriginFromRequest($request)));
}
/**
* 将订单模型转换为统一的创建/详情响应数据
*
* @param string|null $publicOrigin 如 https://api.xxx.com待支付时用于拼完整 pay_url为 null 时仅返回以 / 开头的 path+query
*/
private function buildDepositResponse($order): array
private function buildDepositResponse($order, ?string $publicOrigin = null): array
{
$status = $this->mapDepositStatus($order->status);
$paid = $status === 'paid';
$amount = $this->amountString($order->amount);
$bonus = $this->amountString($order->bonus_amount);
$total = bcadd($amount, $bonus, 4);
$total = bcadd($amount, $bonus, 2);
$on = is_string($order->order_no) ? $order->order_no : strval($order->order_no);
$payUrl = '';
if ($this->intValue($order->status) === 0 && $on !== '') {
$payUrl = DepositMockGateway::payPageUrl($on, $publicOrigin);
}
return [
'order_no' => is_string($order->order_no) ? $order->order_no : strval($order->order_no),
'amount' => $amount,
'bonus_amount' => $bonus,
'total_amount' => $total,
'order_no' => $on,
'amount' => $this->amountNumber($amount),
'bonus_amount' => $this->amountNumber($bonus),
'total_amount' => $this->amountNumber($total),
'status' => $status,
'paid' => $paid,
'pay_channel' => is_string($order->pay_channel) ? $order->pay_channel : strval($order->pay_channel),
'pay_url' => '',
'pay_url' => $payUrl,
'create_time' => is_numeric(strval($order->create_time)) ? intval(strval($order->create_time)) : 0,
'pay_time' => is_numeric(strval($order->pay_time)) ? intval(strval($order->pay_time)) : 0,
];
}
/**
* 将任意金额输入归一化为 4 位小数字符串(不做类型强制转换)
* 根据请求拼出公网 origin用于给客户端直接可用的完整 pay_url。
*/
private function publicOriginFromRequest(Request $request): string
{
$proto = strtolower((string) $request->header('x-forwarded-proto', ''));
$https = $proto === 'https' || strtolower((string) $request->header('x-forwarded-ssl', '')) === 'on';
$scheme = $https ? 'https' : 'http';
$host = trim((string) $request->header('host', ''));
if ($host === '') {
$host = trim((string) ($request->header('x-forwarded-host', '')));
}
if ($host === '') {
$host = '127.0.0.1:8787';
}
return $scheme . '://' . $host;
}
/**
* 模拟第三方支付收银台HTML。玩家浏览器打开点击按钮即向 depositMockNotify 发起回调。
*/
public function depositMockPayPage(Request $request): Response
{
$response = $this->initializeMobile($request);
if ($response !== null) {
return $response;
}
$orderNo = $this->stringParam($request->input('order_no'));
$sign = $this->stringParam($request->input('sign'));
if ($orderNo === '' || $sign === '' || !DepositMockGateway::verifyOrderNo($orderNo, $sign)) {
return response('Invalid or expired payment link', 403, [
'Content-Type' => 'text/plain; charset=utf-8',
]);
}
$order = DepositOrder::where('order_no', $orderNo)->find();
if (!$order) {
return response('Order not found', 404, [
'Content-Type' => 'text/plain; charset=utf-8',
]);
}
DepositOrderExpireService::expirePendingOrders(null, $orderNo);
$order = DepositOrder::where('order_no', $orderNo)->find();
if (!$order) {
return response('Order not found', 404, [
'Content-Type' => 'text/plain; charset=utf-8',
]);
}
if ($this->intValue($order->status) !== 0) {
$st = $this->mapDepositStatus($order->status);
$msg = 'Order status: ' . $st;
if ($st === 'paid') {
$msg = 'This order is already paid. You can return to the app.';
}
$msgEsc = htmlspecialchars($msg, ENT_QUOTES, 'UTF-8');
return response('<!doctype html><html><head><meta charset="utf-8"><title>充值</title></head><body><p>' . $msgEsc . '</p></body></html>', 200, [
'Content-Type' => 'text/html; charset=utf-8',
]);
}
$amount = $this->amountString($order->amount);
$bonus = $this->amountString($order->bonus_amount);
$noEsc = htmlspecialchars($orderNo, ENT_QUOTES, 'UTF-8');
$signEsc = htmlspecialchars($sign, ENT_QUOTES, 'UTF-8');
$payChannel = is_string($order->pay_channel) ? htmlspecialchars($order->pay_channel, ENT_QUOTES, 'UTF-8') : '';
$html = '<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>模拟支付</title></head><body style="font-family:system-ui;padding:1rem">';
$html .= '<h2>模拟第三方收银台</h2>';
$html .= '<p>订单号:' . $noEsc . '</p>';
$html .= '<p>支付渠道:' . $payChannel . '</p>';
$html .= '<p>金额(法币/标价):' . htmlspecialchars($amount, ENT_QUOTES, 'UTF-8') . ' + 赠送 ' . htmlspecialchars($bonus, ENT_QUOTES, 'UTF-8') . '(币)</p>';
$html .= '<p>点击下方按钮即视为<strong>第三方支付成功</strong>,服务端会回调并到账。</p>';
$html .= '<form method="post" action="/api/finance/depositMockNotify" style="margin-top:1rem">';
$html .= '<input type="hidden" name="order_no" value="' . $noEsc . '">';
$html .= '<input type="hidden" name="sign" value="' . $signEsc . '">';
$html .= '<button type="submit" style="padding:0.5rem 1rem">确认支付(模拟成功)</button>';
$html .= '</form></body></html>';
return response($html, 200, [
'Content-Type' => 'text/html; charset=utf-8',
]);
}
/**
* 模拟第三方异步通知:验签后调用 DepositSettlement::settle 入账,并推送 wallet.changed。
*/
public function depositMockNotify(Request $request): Response
{
$response = $this->initializeMobile($request);
if ($response !== null) {
return $response;
}
$orderNo = $this->stringParam($request->input('order_no'));
$sign = $this->stringParam($request->input('sign'));
if ($orderNo === '' || $sign === '') {
return $this->mobileError(1001, 'Missing parameters');
}
if (!DepositMockGateway::verifyOrderNo($orderNo, $sign)) {
return $this->mobileError(1003, 'Invalid parameter value');
}
$order = DepositOrder::where('order_no', $orderNo)->find();
if (!$order) {
return $this->mobileError(2003, 'Order does not exist');
}
DepositOrderExpireService::expirePendingOrders(null, $orderNo);
$order = DepositOrder::where('order_no', $orderNo)->find();
if (!$order) {
return $this->mobileError(2003, 'Order does not exist');
}
if ($this->intValue($order->status) !== 0) {
return $this->mobileSuccess($this->buildDepositResponse($order, null));
}
$orderId = intval(strval($order->id));
if ($orderId <= 0) {
return $this->mobileError(2000, 'Order id invalid');
}
$pc = is_string($order->pay_channel) ? $order->pay_channel : strval($order->pay_channel);
try {
$result = DepositSettlement::settle(
$orderId,
DepositSettlement::SOURCE_THIRD_PARTY,
'mock third party notify',
null,
'channel_code=' . $pc
);
$uid = intval(strval($order->user_id));
if ($uid > 0) {
$coinAfter = is_string($result['balance_after'] ?? null) ? $result['balance_after'] : strval($result['balance_after'] ?? '0');
$credit = is_string($result['credit'] ?? null) ? $result['credit'] : strval($result['credit'] ?? '0');
UserPushService::publish($uid, UserPushService::EVT_WALLET_CHANGED, [
'reason' => 'deposit',
'ref_type' => 'deposit_order',
'ref_id' => (string) $orderId,
'order_no' => $orderNo,
'delta' => $credit,
'balance_after' => $coinAfter,
]);
}
} catch (Throwable $e) {
return $this->mobileError(2000, $e->getMessage());
}
$fresh = DepositOrder::where('order_no', $orderNo)->find();
if (!$fresh) {
return $this->mobileError(2000, 'Order not found after settle');
}
return $this->mobileSuccess($this->buildDepositResponse($fresh, null));
}
/**
* 将任意金额输入归一化为 2 位小数字符串(不做类型强制转换)
*/
private function amountString($raw): string
{
@@ -241,12 +407,17 @@ class Finance extends MobileBase
} elseif (is_int($raw) || is_float($raw)) {
$s = strval($raw);
} else {
return '0.0000';
return '0.00';
}
if ($s === '' || !is_numeric($s)) {
return '0.0000';
return '0.00';
}
return bcadd($s, '0', 4);
return bcadd($s, '0', 2);
}
private function amountNumber($raw): float
{
return floatval($this->amountString($raw));
}
/**
@@ -262,11 +433,12 @@ class Finance extends MobileBase
if ($orderNo === '') {
return $this->mobileError(1001, 'Missing parameters');
}
DepositOrderExpireService::expirePendingOrders(null, $orderNo);
$order = DepositOrder::where('order_no', $orderNo)->where('user_id', $this->auth->id)->find();
if (!$order) {
return $this->mobileError(2003, 'Order does not exist');
}
return $this->mobileSuccess($this->buildDepositResponse($order));
return $this->mobileSuccess($this->buildDepositResponse($order, $this->publicOriginFromRequest($request)));
}
/**
@@ -279,6 +451,7 @@ class Finance extends MobileBase
if ($response !== null) {
return $response;
}
DepositOrderExpireService::expirePendingOrders(intval(strval($this->auth->id)), null);
$page = $this->intValue($request->input('page', 1));
if ($page <= 0) {
$page = 1;
@@ -295,8 +468,8 @@ class Finance extends MobileBase
foreach ($paginate->items() as $row) {
$list[] = [
'order_no' => $row->order_no,
'amount' => $this->amountString($row->amount ?? '0'),
'bonus_amount' => $this->amountString($row->bonus_amount ?? '0'),
'amount' => $this->amountNumber($row->amount ?? '0'),
'bonus_amount' => $this->amountNumber($row->bonus_amount ?? '0'),
'status' => $this->mapDepositStatus($row->status ?? null),
];
}
@@ -324,14 +497,34 @@ class Finance extends MobileBase
if ($withdrawCoin === '' || $receiveAccount === '' || $receiveType === '' || $idempotencyKey === '') {
return $this->mobileError(1001, 'Missing parameters');
}
if (!is_numeric($withdrawCoin) || bccomp($withdrawCoin, '0', 4) <= 0) {
if (mb_strlen($idempotencyKey) > 64) {
return $this->mobileError(1002, 'Idempotency key is too long');
}
if (!is_numeric($withdrawCoin) || bccomp($withdrawCoin, '0', 2) <= 0) {
return $this->mobileError(1001, 'Invalid withdraw amount');
}
$withdrawCoin = bcadd($withdrawCoin, '0', 4);
$withdrawCoin = bcadd($withdrawCoin, '0', 2);
$user = $this->auth->getUser();
$userId = intval(strval($user->id));
// 幂等:相同 idempotency_key 重试直接返回已创建订单
$idemOrder = Db::name('withdraw_order')->where('idempotency_key', $idempotencyKey)->find();
if ($idemOrder) {
$idemUserId = is_numeric(strval($idemOrder['user_id'] ?? null)) ? intval(strval($idemOrder['user_id'])) : 0;
if ($idemUserId !== $userId) {
return $this->mobileError(1002, 'Idempotency key conflict');
}
$idemStatus = $this->intValue($idemOrder['status'] ?? 0);
return $this->mobileSuccess([
'order_no' => is_string($idemOrder['order_no'] ?? null) ? $idemOrder['order_no'] : strval($idemOrder['order_no'] ?? ''),
'status' => $this->mapWithdrawStatus($idemStatus),
'fee_coin' => $this->amountNumber($idemOrder['fee'] ?? '0'),
'actual_arrival_coin' => $this->amountNumber($idemOrder['actual_amount'] ?? '0'),
'risk_review_required' => $idemStatus === 0,
]);
}
// 待审核订单数限制:同一用户最多 MAX_PENDING_WITHDRAW 笔 status=0待审核
$pendingCount = Db::name('withdraw_order')
->where('user_id', $userId)
@@ -344,8 +537,8 @@ class Finance extends MobileBase
]);
}
$balanceBefore = bcadd(strval($user->coin ?? '0'), '0', 4);
if (bccomp($balanceBefore, $withdrawCoin, 4) < 0) {
$balanceBefore = bcadd(strval($user->coin ?? '0'), '0', 2);
if (bccomp($balanceBefore, $withdrawCoin, 2) < 0) {
return $this->mobileError(2001, 'Insufficient balance');
}
@@ -359,14 +552,14 @@ class Finance extends MobileBase
'bet_flow_coin' => $user->bet_flow_coin ?? '0',
]);
$maxWithdrawable = WithdrawFlow::maxWithdrawable($balanceBefore, $flowStatus);
if (bccomp($withdrawCoin, $maxWithdrawable, 4) > 0) {
if (bccomp($withdrawCoin, $maxWithdrawable, 2) > 0) {
return $this->mobileError(2002, 'Withdraw exceeds available bet flow', [
'max_withdrawable' => $maxWithdrawable,
'coin_balance' => $balanceBefore,
'bet_flow_coin' => $flowStatus['bet_flow_coin'],
'total_withdraw_coin' => WithdrawFlow::amountString($user->total_withdraw_coin ?? '0'),
'ratio' => $flowStatus['ratio'],
'max_withdraw_by_flow' => $flowStatus['flow_unlimited'] ? null : $flowStatus['max_withdraw_by_flow'],
'max_withdrawable' => $this->amountNumber($maxWithdrawable),
'coin_balance' => $this->amountNumber($balanceBefore),
'bet_flow_coin' => $this->amountNumber($flowStatus['bet_flow_coin']),
'total_withdraw_coin' => $this->amountNumber(WithdrawFlow::amountString($user->total_withdraw_coin ?? '0')),
'ratio' => floatval($flowStatus['ratio']),
'max_withdraw_by_flow' => $flowStatus['flow_unlimited'] ? null : $this->amountNumber($flowStatus['max_withdraw_by_flow']),
]);
}
@@ -376,9 +569,9 @@ class Finance extends MobileBase
: null;
$orderNo = 'WD' . date('YmdHis') . substr(str_replace('.', '', uniqid('', true)), -6);
$feeCoin = bcmul($withdrawCoin, '0.005', 4);
$actualArrivalCoin = bcsub($withdrawCoin, $feeCoin, 4);
$balanceAfter = bcsub($balanceBefore, $withdrawCoin, 4);
$feeCoin = bcmul($withdrawCoin, '0.005', 2);
$actualArrivalCoin = bcsub($withdrawCoin, $feeCoin, 2);
$balanceAfter = bcsub($balanceBefore, $withdrawCoin, 2);
$now = time();
Db::startTrans();
@@ -399,11 +592,14 @@ class Finance extends MobileBase
$orderId = Db::name('withdraw_order')->insertGetId([
'order_no' => $orderNo,
'idempotency_key' => $idempotencyKey,
'user_id' => $userId,
'channel_id' => $channelId,
'amount' => $withdrawCoin,
'fee' => $feeCoin,
'actual_amount' => $actualArrivalCoin,
'receive_type' => $receiveType,
'receive_account' => $receiveAccount,
'status' => 0,
'review_admin_id' => null,
'review_time' => null,
@@ -436,8 +632,8 @@ class Finance extends MobileBase
return $this->mobileSuccess([
'order_no' => $orderNo,
'status' => 'pending_review',
'fee_coin' => $feeCoin,
'actual_arrival_coin' => $actualArrivalCoin,
'fee_coin' => $this->amountNumber($feeCoin),
'actual_arrival_coin' => $this->amountNumber($actualArrivalCoin),
'risk_review_required' => true,
]);
}
@@ -465,9 +661,11 @@ class Finance extends MobileBase
return $this->mobileSuccess([
'order_no' => $order->order_no,
'status' => $this->mapWithdrawStatus($statusCode),
'withdraw_coin' => $order->amount,
'fee_coin' => $order->fee,
'actual_arrival_coin' => $order->actual_amount,
'withdraw_coin' => $this->amountNumber($order->amount ?? '0'),
'fee_coin' => $this->amountNumber($order->fee ?? '0'),
'actual_arrival_coin' => $this->amountNumber($order->actual_amount ?? '0'),
'receive_type' => is_string($order->receive_type ?? null) ? $order->receive_type : strval($order->receive_type ?? ''),
'receive_account' => is_string($order->receive_account ?? null) ? $order->receive_account : strval($order->receive_account ?? ''),
'reject_reason' => $statusCode === 2 && $remark !== '' ? $remark : null,
'create_time' => $order->create_time,
'review_time' => $order->review_time,
@@ -500,7 +698,7 @@ class Finance extends MobileBase
foreach ($paginate->items() as $row) {
$list[] = [
'order_no' => $row->order_no,
'amount' => $this->amountString($row->amount ?? '0'),
'amount' => $this->amountNumber($row->amount ?? '0'),
'status' => $this->mapWithdrawStatus($row->status ?? null),
];
}
@@ -518,6 +716,19 @@ class Finance extends MobileBase
* 收银台配置:货币列表(含充值/提现汇率、支付渠道pay_channels、提现银行与文案供充值/提现页展示)
*/
public function cashierConfig(Request $request): Response
{
return $this->buildDepositWithdrawConfig($request);
}
/**
* 充值/提现配置(推荐新接口,兼容 cashierConfig 相同返回结构)
*/
public function depositWithdrawConfig(Request $request): Response
{
return $this->buildDepositWithdrawConfig($request);
}
private function buildDepositWithdrawConfig(Request $request): Response
{
$response = $this->initializeMobile($request);
if ($response !== null) {

View File

@@ -59,8 +59,8 @@ class Game extends MobileBase
],
'bet_config' => [
'pick_max_number_count' => $this->getPickMaxNumberCount(),
'chips' => ['1.0000', '5.0000', '10.0000', '25.0000', '50.0000', '100.0000'],
'single_number_max_bet' => $this->getConfigValue('single_number_max_bet', '500.0000'),
'chips' => ['1.00', '5.00', '10.00', '25.00', '50.00', '100.00'],
'single_number_max_bet' => $this->getConfigValue('single_number_max_bet', '500.00'),
],
'dictionary' => $items,
'user_snapshot' => [
@@ -157,10 +157,10 @@ class Game extends MobileBase
if ($periodNo === '' || $betAmount === '' || $idempotencyKey === '') {
return $this->mobileError(1001, 'Missing parameters');
}
if (!is_numeric($betAmount) || bccomp($betAmount, '0', 4) <= 0) {
if (!is_numeric($betAmount) || bccomp($betAmount, '0', 2) <= 0) {
return $this->mobileError(1003, 'Invalid parameter value');
}
$totalAmount = bcadd($betAmount, '0', 4);
$totalAmount = bcadd($betAmount, '0', 2);
$numbers = $this->parseBetNumbersFromRequest($numbersRaw);
if ($numbers === []) {
@@ -189,7 +189,7 @@ class Game extends MobileBase
}
$user = $this->auth->getUser();
if (bccomp((string) $user->coin, $totalAmount, 4) < 0) {
if (bccomp((string) $user->coin, $totalAmount, 2) < 0) {
return $this->mobileError(2001, 'Insufficient balance');
}
@@ -209,7 +209,7 @@ class Game extends MobileBase
return $this->mobileError(5000, 'System is busy, please try again later');
}
$before = (string) ($coinRow['coin'] ?? '0');
if (bccomp($before, $totalAmount, 4) < 0) {
if (bccomp($before, $totalAmount, 2) < 0) {
return $this->mobileError(2001, 'Insufficient balance');
}
@@ -225,7 +225,7 @@ class Game extends MobileBase
}
$now = time();
$after = bcsub($before, $totalAmount, 4);
$after = bcsub($before, $totalAmount, 2);
$orderNo = 'BO' . date('YmdHis') . substr(str_replace('.', '', uniqid('', true)), -6);
$streakAtBet = (int) ($coinRow['current_streak'] ?? 0);
@@ -286,7 +286,7 @@ class Game extends MobileBase
'order_no' => $orderNo,
'period_no' => $period->period_no,
'status' => 'accepted',
'locked_balance' => '0.0000',
'locked_balance' => '0.00',
'balance_after' => $after,
'current_streak' => $streakAtBet,
]);

View File

@@ -26,20 +26,20 @@ class Wallet extends MobileBase
]);
$maxWithdrawable = WithdrawFlow::maxWithdrawable($coinBalance, $flow);
return $this->mobileSuccess([
'coin_balance' => $coinBalance,
'frozen_balance' => '0.0000',
'withdrawable_balance' => $coinBalance,
'max_withdrawable' => $maxWithdrawable,
'total_deposit_coin' => WithdrawFlow::amountString($user->total_deposit_coin ?? '0'),
'total_withdraw_coin' => WithdrawFlow::amountString($user->total_withdraw_coin ?? '0'),
'bet_flow_coin' => $flow['bet_flow_coin'],
'coin_balance' => floatval($coinBalance),
'frozen_balance' => 0.00,
'withdrawable_balance' => floatval($coinBalance),
'max_withdrawable' => floatval($maxWithdrawable),
'total_deposit_coin' => floatval(WithdrawFlow::amountString($user->total_deposit_coin ?? '0')),
'total_withdraw_coin' => floatval(WithdrawFlow::amountString($user->total_withdraw_coin ?? '0')),
'bet_flow_coin' => floatval($flow['bet_flow_coin']),
'withdraw_flow' => [
'ratio' => $flow['ratio'],
'net_deposit' => $flow['net_deposit'],
'required_bet_flow' => $flow['required_bet_flow'],
'remaining_bet_flow' => $flow['remaining_bet_flow'],
'ratio' => floatval($flow['ratio']),
'net_deposit' => floatval($flow['net_deposit']),
'required_bet_flow' => floatval($flow['required_bet_flow']),
'remaining_bet_flow' => floatval($flow['remaining_bet_flow']),
'eligible' => $flow['eligible'],
'max_withdraw_by_flow' => $flow['flow_unlimited'] ? null : $flow['max_withdraw_by_flow'],
'max_withdraw_by_flow' => $flow['flow_unlimited'] ? null : floatval($flow['max_withdraw_by_flow']),
'flow_unlimited' => $flow['flow_unlimited'],
],
]);

View File

@@ -45,6 +45,7 @@ return [
'Order not found after settle' => 'Order not found after settlement',
'Invalid withdraw amount' => 'Invalid withdraw amount',
'Withdraw exceeds available bet flow' => 'The withdraw amount exceeds the available bet-flow quota',
'Too many pending deposit orders' => 'You already have multiple pending deposit orders, please complete payment first or wait for timeout',
'Too many pending withdraw orders' => 'You already have withdraw orders under review, please wait for them to be processed',
// Member center account
'Data updated successfully~' => 'Data updated successfully~',

View File

@@ -77,6 +77,7 @@ return [
'Order not found after settle' => '充值成功后未找到订单',
'Invalid withdraw amount' => '提现金额不合法',
'Withdraw exceeds available bet flow' => '提现金额超出可提现额度',
'Too many pending deposit orders' => '存在多笔待支付充值订单,请先完成支付或等待超时',
'Too many pending withdraw orders' => '用户当前存在多笔提现订单,请等待审核',
// 会员中心 account
'Data updated successfully~' => '资料更新成功~',

View File

@@ -81,11 +81,14 @@ return [
'连胜奖励' => 'Win streak rewards',
'连胜降低档位' => 'Streak reduction tiers',
'钱包加减点' => 'Wallet adjust',
'测试' => 'Test',
'测试频道监听' => 'Test channel monitoring',
'推送-对局公共频道' => 'Push: public game period',
'推送-公告广播频道' => 'Push: operation notices',
'推送-用户私有频道' => 'Push: user private',
'渠道管理' => 'Channel management',
'管理员提现记录' => 'Admin withdraw records',
'一键批量结算待结算渠道' => 'Batch settle pending channels',
'渠道结算统计' => 'Channel settlement statistics',
// 演示/运营公告标题(若入库为菜单展示)
'系统维护通知(演示)' => 'Maintenance notice (demo)',

View File

@@ -80,6 +80,11 @@ class Auth extends \ba\Auth
$this->setError('Account disabled');
return false;
}
$channelId = intval($this->model->channel_id ?? 0);
if ($channelId > 0 && !$this->isChannelEnabled($channelId)) {
$this->setError('Channel disabled');
return false;
}
$this->token = $token;
$this->loginEd = true;
return true;
@@ -136,6 +141,11 @@ class Auth extends \ba\Auth
'remark' => User::formatLoginRemark($time, $ip),
];
$data = array_merge(compact('username', 'password', 'phone', 'email'), $data, $extend);
$channelIdForRegister = isset($data['channel_id']) ? intval($data['channel_id']) : 0;
if ($channelIdForRegister > 0 && !$this->isChannelEnabled($channelIdForRegister)) {
$this->setError('Channel disabled');
return false;
}
Db::startTrans();
try {
@@ -178,6 +188,11 @@ class Auth extends \ba\Auth
$this->setError('Account disabled');
return false;
}
$channelId = intval($this->model->channel_id ?? 0);
if ($channelId > 0 && !$this->isChannelEnabled($channelId)) {
$this->setError('Channel disabled');
return false;
}
$userLoginRetry = config('buildadmin.user_login_retry');
if ($userLoginRetry && $this->model->last_login_time) {
@@ -382,4 +397,13 @@ class Auth extends \ba\Auth
$this->setKeepTime((int)config('buildadmin.user_token_keep_time', 86400));
return true;
}
private function isChannelEnabled(int $channelId): bool
{
$status = Db::name('channel')->where('id', $channelId)->value('status');
if ($status === null || $status === '') {
return false;
}
return intval($status) === 1;
}
}

View File

@@ -0,0 +1,71 @@
<?php
declare(strict_types=1);
namespace app\common\library\finance;
/**
* 模拟第三方支付HMAC 签名的收银台地址 + 回调验签,便于未来替换为真实网关仅改 URL/验签实现。
*/
final class DepositMockGateway
{
/**
* 优先读取环境变量 DEPOSIT_MOCK_HMAC_KEY其次 config('app.deposit_mock_hmac_key'),再使用开发默认值(生产环境务必设置 env
*/
public static function hmacKey(): string
{
$raw = getenv('DEPOSIT_MOCK_HMAC_KEY');
if (is_string($raw) && trim($raw) !== '') {
return trim($raw);
}
$cfg = config('app.deposit_mock_hmac_key', '');
if (is_string($cfg) && $cfg !== '') {
return $cfg;
}
return 'webman-dfw-deposit-mock-dev-key-set-DEPOSIT_MOCK_HMAC_KEY-in-prod';
}
public static function signOrderNo(string $orderNo): string
{
if ($orderNo === '') {
return '';
}
return hash_hmac('sha256', $orderNo, self::hmacKey());
}
public static function verifyOrderNo(string $orderNo, string $sign): bool
{
if ($orderNo === '' || $sign === '') {
return false;
}
$e = self::signOrderNo($orderNo);
if ($e === '') {
return false;
}
return hash_equals($e, $sign);
}
/**
* 玩家浏览器打开的「第三方收银台」地址(本项目中为简单 HTML 模拟页,点击后向 notify 发起 POST 完成入账)。
*
* @param string|null $publicOrigin 如 https://api.example.com为 null 时只返回以 / 开头的 path+query由客户端与 API 域名拼接
*/
public static function payPageUrl(string $orderNo, ?string $publicOrigin = null): string
{
$sign = self::signOrderNo($orderNo);
$q = http_build_query([
'order_no' => $orderNo,
'sign' => $sign,
]);
$path = '/api/finance/depositMockPayPage?' . $q;
if ($publicOrigin === null) {
return $path;
}
$base = rtrim($publicOrigin, '/');
return $base . $path;
}
}

View File

@@ -75,7 +75,7 @@ final class DepositSettlement
// 如果已结算,直接返回已有结果(幂等)
if ($status === 1) {
$userId = is_numeric($order['user_id'] ?? null) ? intval($order['user_id']) : 0;
$coinAfter = '0.0000';
$coinAfter = '0.00';
if ($userId > 0) {
$coin = Db::name('user')->where('id', $userId)->value('coin');
$coinAfter = is_string($coin) ? $coin : strval($coin);
@@ -87,7 +87,7 @@ final class DepositSettlement
'order_no' => $orderNo,
'amount' => $amt,
'bonus_amount' => $bns,
'credit' => bcadd($amt, $bns, 4),
'credit' => bcadd($amt, $bns, 2),
'balance_before' => $coinAfter,
'balance_after' => $coinAfter,
'pay_time' => is_numeric($order['pay_time'] ?? null) ? intval($order['pay_time']) : 0,
@@ -100,14 +100,14 @@ final class DepositSettlement
}
$amount = self::amountString($order['amount'] ?? '0');
if (bccomp($amount, '0', 4) <= 0) {
if (bccomp($amount, '0', 2) <= 0) {
throw new RuntimeException('订单金额异常');
}
$bonus = self::amountString($order['bonus_amount'] ?? '0');
if (bccomp($bonus, '0', 4) < 0) {
$bonus = '0.0000';
if (bccomp($bonus, '0', 2) < 0) {
$bonus = '0.00';
}
$credit = bcadd($amount, $bonus, 4);
$credit = bcadd($amount, $bonus, 2);
$userId = is_numeric($order['user_id'] ?? null) ? intval($order['user_id']) : 0;
if ($userId <= 0) {
@@ -121,7 +121,7 @@ final class DepositSettlement
$channelId = is_numeric($order['channel_id'] ?? null) ? intval($order['channel_id']) : null;
$balanceBefore = self::amountString($user['coin'] ?? '0');
$balanceAfter = bcadd($balanceBefore, $credit, 4);
$balanceAfter = bcadd($balanceBefore, $credit, 2);
$now = time();
$baseRemark = is_string($order['remark'] ?? null) ? $order['remark'] : '';
@@ -142,12 +142,10 @@ final class DepositSettlement
->where('id', $orderId)
->where('status', 0)
->update([
'status' => 1,
'pay_time' => $now,
'review_admin_id' => $operatorAdminId,
'review_time' => $operatorAdminId !== null ? $now : null,
'remark' => $finalRemark,
'update_time' => $now,
'status' => 1,
'pay_time' => $now,
'remark' => $finalRemark,
'update_time' => $now,
]);
if ($affected <= 0) {
throw new RuntimeException('订单状态已变更,请刷新后重试');
@@ -199,7 +197,7 @@ final class DepositSettlement
}
/**
* 将任意数值输入格式化为 4 位小数字符串(不做强制类型转换)
* 将任意数值输入格式化为 2 位小数字符串(不做强制类型转换)
*/
private static function amountString($raw): string
{
@@ -208,11 +206,11 @@ final class DepositSettlement
} elseif (is_int($raw) || is_float($raw)) {
$s = strval($raw);
} else {
return '0.0000';
return '0.00';
}
if (!is_numeric($s)) {
return '0.0000';
return '0.00';
}
return bcadd($s, '0', 4);
return bcadd($s, '0', 2);
}
}

View File

@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace app\common\library\finance;
use app\common\service\GameHotDataRedis;
use support\think\Db;
/**
* 提现打码量(流水)门槛工具库
@@ -25,16 +26,16 @@ final class WithdrawFlow
{
public const CONFIG_KEY = 'withdraw_bet_flow_ratio';
public const DEFAULT_RATIO = '1.0000';
public const DEFAULT_RATIO = '1.00';
/** 当 ratio = 0不限打码max_withdraw_by_flow 用此哨兵表示"无限"。14 位整数位足够覆盖任何业务金额。 */
public const UNLIMITED_FLOW = '99999999999999.9999';
public const UNLIMITED_FLOW = '99999999999999.99';
/** 单用户最多允许同时存在的「待审核」(withdraw_order.status=0) 提现订单数。 */
public const MAX_PENDING_WITHDRAW = 3;
/**
* 读取当前打码倍数(字符串 4 位小数,至少 0
* 读取当前打码倍数(字符串 2 位小数,至少 0
*/
public static function ratio(): string
{
@@ -46,32 +47,32 @@ final class WithdrawFlow
if (!is_string($val) || trim($val) === '' || !is_numeric(trim($val))) {
return self::DEFAULT_RATIO;
}
$normalized = bcadd(trim($val), '0', 4);
if (bccomp($normalized, '0', 4) < 0) {
return '0.0000';
$normalized = bcadd(trim($val), '0', 2);
if (bccomp($normalized, '0', 2) < 0) {
return '0.00';
}
return $normalized;
}
/**
* 归一化金额字段到 4 位小数字符串,非法输入返回 '0.0000'
* 归一化金额字段到 2 位小数字符串,非法输入返回 '0.00'
*/
public static function amountString($raw): string
{
if ($raw === null || $raw === '') {
return '0.0000';
return '0.00';
}
if (is_string($raw)) {
$s = trim($raw);
} elseif (is_int($raw) || is_float($raw)) {
$s = strval($raw);
} else {
return '0.0000';
return '0.00';
}
if (!is_numeric($s)) {
return '0.0000';
return '0.00';
}
return bcadd($s, '0', 4);
return bcadd($s, '0', 2);
}
/**
@@ -108,28 +109,28 @@ final class WithdrawFlow
$withdraw = self::amountString($userSnapshot['total_withdraw_coin'] ?? '0');
$flow = self::amountString($userSnapshot['bet_flow_coin'] ?? '0');
$net = bcsub($deposit, $withdraw, 4);
if (bccomp($net, '0', 4) < 0) {
$net = '0.0000';
$net = bcsub($deposit, $withdraw, 2);
if (bccomp($net, '0', 2) < 0) {
$net = '0.00';
}
$ratio = self::ratio();
$required = bcmul($net, $ratio, 4);
$remaining = bcsub($required, $flow, 4);
if (bccomp($remaining, '0', 4) < 0) {
$remaining = '0.0000';
$required = bcmul($net, $ratio, 2);
$remaining = bcsub($required, $flow, 2);
if (bccomp($remaining, '0', 2) < 0) {
$remaining = '0.00';
}
$eligible = bccomp($flow, $required, 4) >= 0;
$eligible = bccomp($flow, $required, 2) >= 0;
// max_withdraw_by_flow = max(0, bet_flow_coin / ratio - total_withdraw_coin)
$unlimited = bccomp($ratio, '0', 4) === 0;
$unlimited = bccomp($ratio, '0', 2) === 0;
if ($unlimited) {
$maxByFlow = self::UNLIMITED_FLOW;
} else {
$lifetime = bcdiv($flow, $ratio, 4);
$maxByFlow = bcsub($lifetime, $withdraw, 4);
if (bccomp($maxByFlow, '0', 4) < 0) {
$maxByFlow = '0.0000';
$lifetime = bcdiv($flow, $ratio, 2);
$maxByFlow = bcsub($lifetime, $withdraw, 2);
if (bccomp($maxByFlow, '0', 2) < 0) {
$maxByFlow = '0.00';
}
}
@@ -147,18 +148,18 @@ final class WithdrawFlow
/**
* 取单笔最大可提现额 = min(coin_balance, max_withdraw_by_flow)。
* 返回值为 4 位小数字符串,已与 ratio=0不限逻辑兼容。
* 返回值为 2 位小数字符串,已与 ratio=0不限逻辑兼容。
*/
public static function maxWithdrawable(string $coinBalance, array $flowStatus): string
{
$coin = self::amountString($coinBalance);
if (bccomp($coin, '0', 4) < 0) {
$coin = '0.0000';
if (bccomp($coin, '0', 2) < 0) {
$coin = '0.00';
}
if (!empty($flowStatus['flow_unlimited'])) {
return $coin;
}
$byFlow = self::amountString($flowStatus['max_withdraw_by_flow'] ?? '0');
return bccomp($coin, $byFlow, 4) <= 0 ? $coin : $byFlow;
return bccomp($coin, $byFlow, 2) <= 0 ? $coin : $byFlow;
}
}

View File

@@ -10,9 +10,9 @@ use support\think\Db;
/**
* 充值支付渠道:优先读取 game_config.finance_cashier.channels无此键时回退 game_config.deposit_channel迁移期镜像
*
* 每项code须在代码/环境注册表内、sort、status(0/1)、tier_ids空=全部启用档位)
* 每项code须在代码/环境注册表内、sort、status(0/1)
*
* 渠道展示名以代码注册表为准;运营只配置开关排序、可用档位。
* 渠道展示名以代码注册表为准;运营只配置开关排序,默认兼容全部充值档位。
*/
final class DepositChannel
{
@@ -150,23 +150,11 @@ final class DepositChannel
$sort = isset($row['sort']) && is_numeric($row['sort']) ? intval($row['sort']) : 0;
$status = isset($row['status']) && is_numeric($row['status']) ? intval($row['status']) : 1;
$status = $status === 1 ? 1 : 0;
$tierIds = [];
if (isset($row['tier_ids']) && is_array($row['tier_ids'])) {
foreach ($row['tier_ids'] as $tid) {
if (is_string($tid)) {
$t = trim($tid);
if ($t !== '' && preg_match('/^[a-zA-Z0-9_\-]{1,32}$/', $t)) {
$tierIds[] = $t;
}
}
}
$tierIds = array_values(array_unique($tierIds));
}
$out[] = [
'code' => $code,
'sort' => $sort,
'status' => $status,
'tier_ids' => $tierIds,
'tier_ids' => [],
];
}
@@ -219,17 +207,8 @@ final class DepositChannel
*/
public static function isTierAllowed(array $overrideRow, string $tierId): bool
{
$ids = $overrideRow['tier_ids'] ?? [];
if (!is_array($ids) || $ids === []) {
return true;
}
foreach ($ids as $id) {
if (is_string($id) && $id === $tierId) {
return true;
}
}
return false;
// 渠道不再配置档位白名单:默认兼容全部充值档位。
return true;
}
/**
@@ -268,9 +247,6 @@ final class DepositChannel
if (!isset($registry[$code])) {
continue;
}
if (!self::isTierAllowed($row, $tierId)) {
continue;
}
$meta = $registry[$code];
$name = self::pickLangName($meta, $lang);
$sortRaw = $row['sort'] ?? 0;

View File

@@ -14,9 +14,9 @@ use InvalidArgumentException;
* - title : string档位中文名称必填前端中文环境展示
* - title_en : string档位英文名称可选前端英文环境展示为空时回退到 title
* - currency : string支付货币代码38 位大写字母,如 MYR、CNY
* - pay_amount : string玩家支付的法币/支付货币额度(4 位小数)
* - amount : string到账基础平台币4 位小数)
* - bonus_amount : string赠送平台币4 位小数,可为 0
* - pay_amount : string玩家支付的法币/支付货币额度(2 位小数)
* - amount : string到账基础平台币2 位小数)
* - bonus_amount : string赠送平台币2 位小数,可为 0
* - desc : string档位中文描述可空<=255
* - desc_en : string档位英文描述可空<=255为空时回退到 desc
* - sort : int排序权重小值在前
@@ -95,7 +95,7 @@ final class DepositTier
$payAmount = self::normalizeAmount($row['pay_amount'] ?? '');
$amount = self::normalizeAmount($row['amount'] ?? '');
$bonus = self::normalizeAmount($row['bonus_amount'] ?? '0');
if (bccomp($payAmount, '0', 4) <= 0 && bccomp($amount, '0', 4) > 0) {
if (bccomp($payAmount, '0', 2) <= 0 && bccomp($amount, '0', 2) > 0) {
// 历史数据仅有 amount平台币用占位同步 pay_amount运营应在后台改为真实支付额度
$payAmount = $amount;
}
@@ -187,17 +187,17 @@ final class DepositTier
}
$payAmount = self::normalizeAmount($row['pay_amount'] ?? '');
if (bccomp($payAmount, '0', 4) <= 0) {
if (bccomp($payAmount, '0', 2) <= 0) {
throw new InvalidArgumentException('第 ' . $no . ' 行支付货币额度必须大于 0');
}
$amount = self::normalizeAmount($row['amount'] ?? '');
if (bccomp($amount, '0', 4) <= 0) {
if (bccomp($amount, '0', 2) <= 0) {
throw new InvalidArgumentException('第 ' . $no . ' 行基础平台币到账必须大于 0');
}
$bonus = self::normalizeAmount($row['bonus_amount'] ?? '0');
if (bccomp($bonus, '0', 4) < 0) {
if (bccomp($bonus, '0', 2) < 0) {
throw new InvalidArgumentException('第 ' . $no . ' 行赠送金额不能为负数');
}
@@ -333,25 +333,25 @@ final class DepositTier
}
/**
* 将金额归一化为 4 位小数字符串;非法输入返回 '0.0000'
* 将金额归一化为 2 位小数字符串;非法输入返回 '0.00'
*/
public static function normalizeAmount($raw): string
{
if ($raw === null || $raw === '') {
return '0.0000';
return '0.00';
}
if (is_string($raw)) {
$s = trim($raw);
} elseif (is_int($raw) || is_float($raw)) {
$s = strval($raw);
} else {
return '0.0000';
return '0.00';
}
$s = str_replace(',', '.', $s);
if (!is_numeric($s)) {
return '0.0000';
return '0.00';
}
return bcadd($s, '0', 4);
return bcadd($s, '0', 2);
}
/**

View File

@@ -353,10 +353,10 @@ final class FinanceCashierConfig
$seenCodes[$code] = true;
$dep = $row['deposit_coins_per_fiat'] ?? '';
$wdr = $row['withdraw_coins_per_fiat'] ?? '';
if (!is_string($dep) || $dep === '' || !is_numeric($dep) || bccomp($dep, '0', 8) <= 0) {
if (!is_string($dep) || $dep === '' || !is_numeric($dep) || bccomp($dep, '0', 2) <= 0) {
throw new InvalidArgumentException('第 ' . ($idx + 1) . ' 行:充值汇率须为大于 0 的数字');
}
if (!is_string($wdr) || $wdr === '' || !is_numeric($wdr) || bccomp($wdr, '0', 8) <= 0) {
if (!is_string($wdr) || $wdr === '' || !is_numeric($wdr) || bccomp($wdr, '0', 2) <= 0) {
throw new InvalidArgumentException('第 ' . ($idx + 1) . ' 行:提现汇率须为大于 0 的数字');
}
}
@@ -379,7 +379,7 @@ final class FinanceCashierConfig
if (isset($p['withdraw_limits']) && is_array($p['withdraw_limits'])) {
foreach (['min_ewallet', 'min_bank'] as $k) {
$v = $p['withdraw_limits'][$k] ?? '0';
if (!is_string($v) || !is_numeric($v) || bccomp($v, '0', 4) < 0) {
if (!is_string($v) || !is_numeric($v) || bccomp($v, '0', 2) < 0) {
throw new InvalidArgumentException('提现最低限额须为不小于 0 的数字');
}
}

View File

@@ -147,7 +147,7 @@ final class StreakWinReward
}
/**
* 返回该注单适用的「赔率乘数」字符串(= 配置档位的 odds_factor供 bcmul(total_amount, ..., 4)。
* 返回该注单适用的「赔率乘数」字符串(= 配置档位的 odds_factor供 bcmul(total_amount, ..., 2)。
*/
public static function totalOddsMultiplierForStreakAtBet(int $streakAtBet): string
{
@@ -156,7 +156,7 @@ final class StreakWinReward
$factor = 1;
}
return bcadd((string) $factor, '0', 4);
return bcadd((string) $factor, '0', 2);
}
/**

View File

@@ -0,0 +1,27 @@
<?php
namespace app\common\model;
use support\think\Model;
class AdminWallet extends Model
{
protected $name = 'admin_wallet';
protected $autoWriteTimestamp = true;
protected $type = [
'create_time' => 'integer',
'update_time' => 'integer',
'balance' => 'string',
'frozen_balance' => 'string',
'total_income' => 'string',
'total_withdraw' => 'string',
];
public function admin(): \think\model\relation\BelongsTo
{
return $this->belongsTo(\app\admin\model\Admin::class, 'admin_id', 'id');
}
}

View File

@@ -0,0 +1,39 @@
<?php
namespace app\common\model;
use support\think\Model;
class AdminWalletRecord extends Model
{
protected $name = 'admin_wallet_record';
protected $autoWriteTimestamp = false;
protected $createTime = 'create_time';
protected $updateTime = false;
protected $type = [
'create_time' => 'integer',
'amount' => 'string',
'balance_before' => 'string',
'balance_after' => 'string',
];
public function admin(): \think\model\relation\BelongsTo
{
return $this->belongsTo(\app\admin\model\Admin::class, 'admin_id', 'id');
}
public function channel(): \think\model\relation\BelongsTo
{
return $this->belongsTo(Channel::class, 'channel_id', 'id');
}
public function operatorAdmin(): \think\model\relation\BelongsTo
{
return $this->belongsTo(\app\admin\model\Admin::class, 'operator_admin_id', 'id');
}
}

View File

@@ -0,0 +1,37 @@
<?php
namespace app\common\model;
use support\think\Model;
class AdminWithdrawOrder extends Model
{
protected $name = 'admin_withdraw_order';
protected $autoWriteTimestamp = true;
protected $type = [
'create_time' => 'integer',
'update_time' => 'integer',
'review_time' => 'integer',
'amount' => 'string',
'actual_amount' => 'string',
'status' => 'integer',
];
public function admin(): \think\model\relation\BelongsTo
{
return $this->belongsTo(\app\admin\model\Admin::class, 'admin_id', 'id');
}
public function channel(): \think\model\relation\BelongsTo
{
return $this->belongsTo(Channel::class, 'channel_id', 'id');
}
public function reviewAdmin(): \think\model\relation\BelongsTo
{
return $this->belongsTo(\app\admin\model\Admin::class, 'review_admin_id', 'id');
}
}

View File

@@ -0,0 +1,213 @@
<?php
declare(strict_types=1);
namespace app\common\service;
use support\think\Db;
class AdminWalletService
{
public static function ensureWallet(int $adminId): array
{
$wallet = Db::name('admin_wallet')->where('admin_id', $adminId)->find();
if (is_array($wallet)) {
return $wallet;
}
$now = time();
Db::name('admin_wallet')->insert([
'admin_id' => $adminId,
'balance' => '0.00',
'frozen_balance' => '0.00',
'total_income' => '0.00',
'total_withdraw' => '0.00',
'create_time' => $now,
'update_time' => $now,
]);
return Db::name('admin_wallet')->where('admin_id', $adminId)->find() ?: [];
}
public static function creditCommission(int $adminId, ?int $channelId, string $amount, string $refType, int $refId, string $remark): void
{
$wallet = self::ensureWallet($adminId);
$before = strval($wallet['balance'] ?? '0.00');
$after = bcadd($before, $amount, 2);
$now = time();
Db::name('admin_wallet')->where('admin_id', $adminId)->update([
'balance' => $after,
'total_income' => Db::raw('total_income + ' . $amount),
'update_time' => $now,
]);
Db::name('admin_wallet_record')->insert([
'admin_id' => $adminId,
'channel_id' => $channelId,
'biz_type' => 'commission_income',
'direction' => 1,
'amount' => $amount,
'balance_before' => $before,
'balance_after' => $after,
'ref_type' => $refType,
'ref_id' => $refId,
'idempotency_key' => 'commission_income_' . $adminId . '_' . $refId,
'operator_admin_id' => null,
'remark' => $remark,
'create_time' => $now,
]);
}
public static function applyWithdraw(
int $adminId,
int $channelId,
string $withdrawCoin,
string $receiveType,
string $receiveAccount,
string $idempotencyKey,
string $remark
): array
{
$existing = Db::name('admin_withdraw_order')->where('idempotency_key', $idempotencyKey)->find();
if (is_array($existing)) {
$existAdminId = intval($existing['admin_id'] ?? 0);
if ($existAdminId !== $adminId) {
return ['ok' => false, 'msg' => 'Idempotency key conflict'];
}
return [
'ok' => true,
'order_id' => intval($existing['id'] ?? 0),
'order_no' => strval($existing['order_no'] ?? ''),
'idempotent_hit' => true,
];
}
$wallet = self::ensureWallet($adminId);
$before = strval($wallet['balance'] ?? '0.00');
if (bccomp($before, $withdrawCoin, 2) < 0) {
return ['ok' => false, 'msg' => '钱包余额不足'];
}
$after = bcsub($before, $withdrawCoin, 2);
$beforeFrozen = strval($wallet['frozen_balance'] ?? '0.00');
$afterFrozen = bcadd($beforeFrozen, $withdrawCoin, 2);
$now = time();
$orderNo = 'AWD' . date('YmdHis') . str_pad(strval($adminId), 6, '0', STR_PAD_LEFT) . strval(random_int(1000, 9999));
Db::name('admin_wallet')->where('admin_id', $adminId)->update([
'balance' => $after,
'frozen_balance' => $afterFrozen,
'update_time' => $now,
]);
$orderId = Db::name('admin_withdraw_order')->insertGetId([
'order_no' => $orderNo,
'admin_id' => $adminId,
'channel_id' => $channelId > 0 ? $channelId : null,
'amount' => $withdrawCoin,
'actual_amount' => $withdrawCoin,
'status' => 0,
'receive_type' => $receiveType,
'receive_account' => $receiveAccount,
'idempotency_key' => $idempotencyKey,
'review_admin_id' => null,
'review_time' => null,
'remark' => $remark,
'create_time' => $now,
'update_time' => $now,
]);
Db::name('admin_wallet_record')->insert([
'admin_id' => $adminId,
'channel_id' => $channelId > 0 ? $channelId : null,
'biz_type' => 'withdraw_freeze',
'direction' => 2,
'amount' => $withdrawCoin,
'balance_before' => $before,
'balance_after' => $after,
'ref_type' => 'admin_withdraw_order',
'ref_id' => $orderId,
'idempotency_key' => 'admin_withdraw_freeze_' . $orderId,
'operator_admin_id' => $adminId,
'remark' => $remark !== '' ? $remark : '管理员提现申请冻结',
'create_time' => $now,
]);
return ['ok' => true, 'order_id' => $orderId, 'order_no' => $orderNo];
}
public static function approveWithdraw(array $order, int $reviewAdminId, string $remark): void
{
$orderId = intval($order['id'] ?? 0);
$adminId = intval($order['admin_id'] ?? 0);
$amount = strval($order['amount'] ?? '0.00');
$wallet = self::ensureWallet($adminId);
$frozen = strval($wallet['frozen_balance'] ?? '0.00');
$afterFrozen = bcsub($frozen, $amount, 2);
$now = time();
Db::name('admin_wallet')->where('admin_id', $adminId)->update([
'frozen_balance' => $afterFrozen,
'total_withdraw' => Db::raw('total_withdraw + ' . $amount),
'update_time' => $now,
]);
Db::name('admin_withdraw_order')->where('id', $orderId)->update([
'status' => 1,
'review_admin_id' => $reviewAdminId,
'review_time' => $now,
'remark' => $remark,
'update_time' => $now,
]);
Db::name('admin_wallet_record')->insert([
'admin_id' => $adminId,
'channel_id' => $order['channel_id'] ?? null,
'biz_type' => 'withdraw_success',
'direction' => 2,
'amount' => $amount,
'balance_before' => strval($wallet['balance'] ?? '0.00'),
'balance_after' => strval($wallet['balance'] ?? '0.00'),
'ref_type' => 'admin_withdraw_order',
'ref_id' => $orderId,
'idempotency_key' => 'admin_withdraw_success_' . $orderId,
'operator_admin_id' => $reviewAdminId,
'remark' => $remark !== '' ? $remark : '管理员提现审核通过',
'create_time' => $now,
]);
}
public static function rejectWithdraw(array $order, int $reviewAdminId, string $remark): void
{
$orderId = intval($order['id'] ?? 0);
$adminId = intval($order['admin_id'] ?? 0);
$amount = strval($order['amount'] ?? '0.00');
$wallet = self::ensureWallet($adminId);
$before = strval($wallet['balance'] ?? '0.00');
$after = bcadd($before, $amount, 2);
$frozen = strval($wallet['frozen_balance'] ?? '0.00');
$afterFrozen = bcsub($frozen, $amount, 2);
$now = time();
Db::name('admin_wallet')->where('admin_id', $adminId)->update([
'balance' => $after,
'frozen_balance' => $afterFrozen,
'update_time' => $now,
]);
Db::name('admin_withdraw_order')->where('id', $orderId)->update([
'status' => 2,
'review_admin_id' => $reviewAdminId,
'review_time' => $now,
'remark' => $remark,
'update_time' => $now,
]);
Db::name('admin_wallet_record')->insert([
'admin_id' => $adminId,
'channel_id' => $order['channel_id'] ?? null,
'biz_type' => 'withdraw_refund',
'direction' => 1,
'amount' => $amount,
'balance_before' => $before,
'balance_after' => $after,
'ref_type' => 'admin_withdraw_order',
'ref_id' => $orderId,
'idempotency_key' => 'admin_withdraw_refund_' . $orderId,
'operator_admin_id' => $reviewAdminId,
'remark' => $remark !== '' ? $remark : '管理员提现审核拒绝退回',
'create_time' => $now,
]);
}
}

View File

@@ -0,0 +1,470 @@
<?php
declare(strict_types=1);
namespace app\common\service;
use support\think\Db;
use Throwable;
class ChannelSettlementService
{
public static function settleBySuperAdmin(int $channelId, int $operatorAdminId, string $remark = '', bool $auto = false): array
{
$channel = Db::name('channel')->where('id', $channelId)->find();
if (!is_array($channel)) {
return ['ok' => false, 'msg' => '渠道不存在'];
}
$payload = self::buildSettlePayload($channel);
if (is_string($payload)) {
return ['ok' => false, 'msg' => $payload];
}
$settlementNo = self::generateAgentSettlementNo($auto ? 'A' : 'M', $channelId, intval($payload['period_end_ts']));
if (Db::name('agent_settlement_period')->where('settlement_no', $settlementNo)->value('id')) {
return ['ok' => false, 'msg' => '结算单号冲突,请重试'];
}
$shareRows = self::resolveCommissionSharesForChannel($channelId);
if ($shareRows === []) {
return ['ok' => false, 'msg' => '渠道下无可用管理员分配比例,无法结算'];
}
$now = time();
Db::startTrans();
try {
$periodId = intval(Db::name('agent_settlement_period')->insertGetId([
'settlement_no' => $settlementNo,
'period_start_at' => $payload['period_start_ts'],
'period_end_at' => $payload['period_end_ts'],
'total_bet_amount' => $payload['total_bet_amount'],
'total_payout_amount' => $payload['total_payout_amount'],
'platform_profit_amount' => $payload['platform_profit_amount'],
'status' => 1,
'remark' => $remark !== '' ? $remark : (($auto ? '自动' : '手动') . '渠道结算-CH' . $channelId),
'create_time' => $now,
'update_time' => $now,
]));
$rows = self::buildCommissionRowsForSplit(
$shareRows,
$channelId,
$periodId,
strval($payload['calc_base_amount']),
strval($payload['commission_amount']),
$remark !== '' ? $remark : '渠道待分红记录',
$now
);
if ($rows === []) {
throw new \RuntimeException('生成待分红记录失败');
}
Db::name('agent_commission_record')->insertAll($rows);
Db::name('channel')->where('id', $channelId)->update([
'carryover_balance' => Db::raw('carryover_balance + ' . strval($payload['commission_amount'])),
'update_time' => $now,
]);
Db::commit();
} catch (Throwable $e) {
Db::rollback();
return ['ok' => false, 'msg' => $e->getMessage()];
}
return ['ok' => true, 'payload' => $payload];
}
public static function settleDividendByChannelAdmin(int $channelId, int $operatorAdminId, string $remark = ''): array
{
$channel = Db::name('channel')->where('id', $channelId)->find();
if (!is_array($channel)) {
return ['ok' => false, 'msg' => '渠道不存在'];
}
$carryover = strval($channel['carryover_balance'] ?? '0.00');
if (bccomp($carryover, '0', 2) <= 0) {
return ['ok' => false, 'msg' => '当前渠道没有分红余额,待下周期结算'];
}
$pendingRows = Db::name('agent_commission_record')
->where('channel_id', $channelId)
->where('status', 0)
->order('id', 'asc')
->select()
->toArray();
if ($pendingRows === []) {
return ['ok' => false, 'msg' => '当前渠道没有待分红记录,待下周期结算'];
}
$totalPending = '0.00';
foreach ($pendingRows as $pendingRow) {
$totalPending = bcadd($totalPending, strval($pendingRow['commission_amount'] ?? '0.00'), 2);
}
if (bccomp($carryover, $totalPending, 2) < 0) {
return ['ok' => false, 'msg' => '渠道可分红余额不足,请联系超管核对结算'];
}
$now = time();
Db::startTrans();
try {
foreach ($pendingRows as $pendingRow) {
$amount = strval($pendingRow['commission_amount'] ?? '0.00');
$adminId = intval($pendingRow['admin_id'] ?? 0);
if ($adminId <= 0 || bccomp($amount, '0', 2) <= 0) {
continue;
}
AdminWalletService::creditCommission(
$adminId,
$channelId,
$amount,
'agent_commission_record',
intval($pendingRow['id'] ?? 0),
$remark !== '' ? $remark : '渠道分红结算入账'
);
}
Db::name('agent_commission_record')
->where('channel_id', $channelId)
->where('status', 0)
->update([
'status' => 1,
'settled_at' => $now,
'update_time' => $now,
'remark' => Db::raw("CONCAT(remark, ' | 渠道结算确认')"),
]);
Db::name('channel')->where('id', $channelId)->update([
'carryover_balance' => bcsub($carryover, $totalPending, 2),
'update_time' => $now,
]);
$periodIds = Db::name('agent_commission_record')->where('channel_id', $channelId)->where('status', 1)->column('settlement_period_id');
if ($periodIds !== []) {
foreach ($periodIds as $periodIdRaw) {
$periodId = intval($periodIdRaw);
if ($periodId <= 0) {
continue;
}
$left = intval(Db::name('agent_commission_record')->where('settlement_period_id', $periodId)->where('status', 0)->count());
if ($left === 0) {
Db::name('agent_settlement_period')->where('id', $periodId)->update([
'status' => 2,
'update_time' => $now,
]);
}
}
}
Db::commit();
} catch (Throwable $e) {
Db::rollback();
return ['ok' => false, 'msg' => $e->getMessage()];
}
return ['ok' => true, 'settled_amount' => $totalPending];
}
public static function settleAllDueChannels(int $operatorAdminId): array
{
$channels = Db::name('channel')->where('status', 1)->select()->toArray();
$ok = 0;
$failed = [];
$now = time();
foreach ($channels as $channel) {
$channelId = intval($channel['id'] ?? 0);
if ($channelId <= 0) {
continue;
}
if (!self::isChannelDueForAutoSettle($channel, $now)) {
continue;
}
$res = self::settleBySuperAdmin($channelId, $operatorAdminId, '周期自动结算', true);
if (($res['ok'] ?? false) === true) {
$ok++;
continue;
}
$failed[] = [
'channel_id' => $channelId,
'msg' => strval($res['msg'] ?? '结算失败'),
];
}
return ['ok_count' => $ok, 'failed' => $failed];
}
private static function isChannelDueForAutoSettle(array $channel, int $now): bool
{
$channelId = intval($channel['id'] ?? 0);
if ($channelId <= 0) {
return false;
}
$lastEnd = self::getLastSettlementEndForChannel($channelId);
$cycle = strval($channel['settle_cycle'] ?? 'weekly');
$settleTime = strval($channel['settle_time'] ?? '02:00:00');
$today = date('Y-m-d', $now);
$targetTs = strtotime($today . ' ' . $settleTime);
if ($targetTs === false || $now < $targetTs) {
return false;
}
if ($lastEnd !== null && $lastEnd >= $targetTs) {
return false;
}
if ($cycle === 'daily') {
return true;
}
if ($cycle === 'weekly') {
$weekday = intval($channel['settle_weekday'] ?? 1);
$w = intval(date('N', $now));
return $weekday === $w;
}
if ($cycle === 'monthly') {
$monthday = intval($channel['settle_monthday'] ?? 1);
$d = intval(date('j', $now));
return $monthday === $d;
}
return false;
}
public static function buildSettlePayload(array $row): array|string
{
$channelId = intval($row['id'] ?? 0);
if ($channelId <= 0) {
return '渠道数据异常';
}
$endTs = time();
$lastEnd = self::getLastSettlementEndForChannel($channelId);
$channelCreateTs = intval($row['create_time'] ?? 0);
$periodStartTs = $lastEnd === null ? ($channelCreateTs > 0 ? $channelCreateTs : 0) : $lastEnd;
if ($periodStartTs >= $endTs) {
return '结算区间无效(开始时间不早于当前)';
}
$stats = self::aggregateBetOrderForChannel($channelId, $periodStartTs, $lastEnd !== null, $endTs);
$totalBet = $stats['total_bet'];
$totalPayout = $stats['total_payout'];
$profit = bcsub($totalBet, $totalPayout, 2);
$mode = strval($row['agent_mode'] ?? 'turnover');
$commission = self::computeCommissionAmounts($row, $totalBet, $profit, $mode);
if (is_string($commission)) {
return $commission;
}
return [
'period_start_ts' => $periodStartTs,
'period_end_ts' => $endTs,
'period_start_at' => date('Y-m-d H:i:s', $periodStartTs),
'period_end_at' => date('Y-m-d H:i:s', $endTs),
'total_bet_amount' => $totalBet,
'total_payout_amount' => $totalPayout,
'platform_profit_amount' => $profit,
'commission_rate' => $commission['commission_rate'],
'calc_base_amount' => $commission['calc_base_amount'],
'commission_amount' => $commission['commission_amount'],
'agent_mode' => $mode,
'commission_split' => self::buildCommissionSplitPreview(self::resolveCommissionSharesForChannel($channelId), $commission['commission_amount']),
];
}
private static function getLastSettlementEndForChannel(int $channelId): ?int
{
$row = Db::name('agent_commission_record')->alias('acr')
->join('agent_settlement_period asp', 'acr.settlement_period_id = asp.id')
->where('acr.channel_id', $channelId)
->field('MAX(asp.period_end_at) AS m')
->find();
if (!is_array($row)) {
return null;
}
$m = $row['m'] ?? null;
if ($m === null || $m === '') {
return null;
}
return intval($m);
}
private static function aggregateBetOrderForChannel(int $channelId, int $periodStartTs, bool $hasPriorSettlement, int $endTs): array
{
$query = Db::name('bet_order')
->where('channel_id', $channelId)
->where('status', 2)
->where('create_time', '<=', $endTs);
if ($hasPriorSettlement) {
$query->where('create_time', '>', $periodStartTs);
} else {
$query->where('create_time', '>=', $periodStartTs);
}
$row = $query->field('SUM(total_amount) AS tb, SUM(win_amount) AS tw, SUM(jackpot_extra_amount) AS tj')->find();
$tb = is_array($row) && $row['tb'] !== null && $row['tb'] !== '' ? strval($row['tb']) : '0.00';
$tw = is_array($row) && $row['tw'] !== null && $row['tw'] !== '' ? strval($row['tw']) : '0.00';
$tj = is_array($row) && $row['tj'] !== null && $row['tj'] !== '' ? strval($row['tj']) : '0.00';
$totalPayout = bcadd($tw, $tj, 2);
return ['total_bet' => bcadd($tb, '0', 2), 'total_payout' => bcadd($totalPayout, '0', 2)];
}
private static function computeCommissionAmounts(array $row, string $totalBet, string $platformProfit, string $mode): array|string
{
if ($mode === 'turnover') {
$ratePercent = $row['turnover_share_rate'] ?? null;
if ($ratePercent === null || $ratePercent === '') {
return '普通返水代理未配置返水分红比例';
}
$rateDec = bcdiv(strval($ratePercent), '100', 4);
return [
'commission_rate' => $rateDec,
'calc_base_amount' => $totalBet,
'commission_amount' => bcmul($totalBet, $rateDec, 2),
];
}
if ($mode === 'affiliate') {
$fee = $row['affiliate_fee_rate'] ?? null;
$rulesRaw = $row['affiliate_ladder_rules'] ?? null;
if ($fee === null || $fee === '') {
return '联营代理未配置成本扣除比例';
}
$rules = self::normalizeLadderRulesForSettlement($rulesRaw);
if ($rules === []) {
return '联营阶梯规则无效或为空';
}
if (bccomp($platformProfit, '0', 2) <= 0) {
return ['commission_rate' => '0.0000', 'calc_base_amount' => '0.00', 'commission_amount' => '0.00'];
}
$afterFee = bcmul($platformProfit, bcsub('1', strval($fee), 4), 2);
if (bccomp($afterFee, '0', 2) <= 0) {
return ['commission_rate' => '0.0000', 'calc_base_amount' => '0.00', 'commission_amount' => '0.00'];
}
$shareRate = self::pickAffiliateShareRateFromLadder($rules, $platformProfit);
$rateDec = number_format($shareRate, 6, '.', '');
return [
'commission_rate' => $rateDec,
'calc_base_amount' => $afterFee,
'commission_amount' => bcmul($afterFee, $rateDec, 2),
];
}
return '未知的代理模式';
}
private static function normalizeLadderRulesForSettlement(mixed $rulesRaw): array
{
if ($rulesRaw === null || $rulesRaw === '') {
return [];
}
if (is_string($rulesRaw)) {
$decoded = json_decode($rulesRaw, true);
$rulesRaw = is_array($decoded) ? $decoded : [];
}
if (!is_array($rulesRaw)) {
return [];
}
$out = [];
foreach ($rulesRaw as $rule) {
if (!is_array($rule)) {
continue;
}
$minLoss = $rule['minLoss'] ?? ($rule['min_loss'] ?? null);
$shareRate = $rule['shareRate'] ?? ($rule['share_rate'] ?? null);
if ($minLoss === null || $shareRate === null || !is_numeric(strval($minLoss)) || !is_numeric(strval($shareRate))) {
continue;
}
$out[] = [
'minLoss' => number_format(floatval($minLoss), 4, '.', ''),
'shareRate' => number_format(floatval($shareRate), 6, '.', ''),
];
}
usort($out, static function (array $a, array $b): int {
return bccomp($a['minLoss'], $b['minLoss'], 4);
});
return $out;
}
private static function pickAffiliateShareRateFromLadder(array $rules, string $playerLoss): float
{
$chosen = floatval($rules[0]['shareRate']);
foreach ($rules as $rule) {
if (bccomp($playerLoss, strval($rule['minLoss']), 2) >= 0) {
$chosen = floatval($rule['shareRate']);
}
}
return $chosen;
}
private static function generateAgentSettlementNo(string $sourceFlag, int $channelId, int $endTs): string
{
$flag = strtoupper(trim($sourceFlag));
if ($flag !== 'M' && $flag !== 'A') {
$flag = 'M';
}
$base = $flag . str_pad(strval(max(0, $channelId)), 6, '0', STR_PAD_LEFT) . str_pad(strval(max(0, $endTs)), 10, '0', STR_PAD_LEFT);
return $base . strtoupper(substr(bin2hex(random_bytes(4)), 0, 2));
}
private static function resolveCommissionSharesForChannel(int $channelId): array
{
$rows = Db::name('channel_admin_share')->alias('cas')
->join('admin a', 'cas.admin_id = a.id')
->field(['cas.admin_id', 'cas.share_rate'])
->where('cas.channel_id', $channelId)
->where('cas.status', 1)
->where('a.status', 'enable')
->order('cas.admin_id', 'asc')
->select()
->toArray();
if ($rows === []) {
return [];
}
$sum = '0.00';
$out = [];
foreach ($rows as $row) {
$adminId = intval($row['admin_id'] ?? 0);
$shareRate = bcadd(strval($row['share_rate'] ?? '0'), '0', 2);
if ($adminId <= 0 || bccomp($shareRate, '0', 2) <= 0) {
continue;
}
$sum = bcadd($sum, $shareRate, 2);
$out[] = ['admin_id' => $adminId, 'share_rate' => $shareRate];
}
if ($out === [] || bccomp($sum, '100.00', 2) !== 0) {
return [];
}
return $out;
}
private static function buildCommissionRowsForSplit(array $shareRows, int $channelId, int $periodId, string $calcBaseAmount, string $commissionTotal, string $remark, int $now): array
{
$sum = '0.00';
$rows = [];
$lastIndex = count($shareRows) - 1;
foreach ($shareRows as $index => $shareRow) {
$shareRate = bcadd(strval($shareRow['share_rate'] ?? '0.00'), '0', 2);
$shareDec = bcdiv($shareRate, '100', 4);
$amount = $index === $lastIndex ? bcsub($commissionTotal, $sum, 2) : bcmul($commissionTotal, $shareDec, 2);
if ($index !== $lastIndex) {
$sum = bcadd($sum, $amount, 2);
}
$effectiveRate = bccomp($calcBaseAmount, '0', 2) <= 0 ? '0.0000' : bcdiv($amount, $calcBaseAmount, 6);
$rows[] = [
'settlement_period_id' => $periodId,
'channel_id' => $channelId,
'admin_id' => intval($shareRow['admin_id'] ?? 0),
'commission_rate' => $effectiveRate,
'calc_base_amount' => $calcBaseAmount,
'commission_amount' => $amount,
'status' => 0,
'settled_at' => null,
'remark' => $remark . ' | 分配比例=' . $shareRate . '%',
'create_time' => $now,
'update_time' => $now,
];
}
return $rows;
}
private static function buildCommissionSplitPreview(array $shareRows, string $commissionTotal): array
{
if ($shareRows === []) {
return [];
}
$adminIds = array_map(static fn(array $row): int => intval($row['admin_id'] ?? 0), $shareRows);
$adminNames = Db::name('admin')->where('id', 'in', $adminIds)->column('username', 'id');
$sum = '0.00';
$out = [];
$lastIndex = count($shareRows) - 1;
foreach ($shareRows as $index => $shareRow) {
$shareRate = bcadd(strval($shareRow['share_rate'] ?? '0.00'), '0', 2);
$shareDec = bcdiv($shareRate, '100', 4);
$amount = $index === $lastIndex ? bcsub($commissionTotal, $sum, 2) : bcmul($commissionTotal, $shareDec, 2);
if ($index !== $lastIndex) {
$sum = bcadd($sum, $amount, 2);
}
$aid = intval($shareRow['admin_id'] ?? 0);
$out[] = [
'admin_id' => $aid,
'admin_username' => strval($adminNames[$aid] ?? ('#' . $aid)),
'share_rate' => $shareRate,
'commission_amount' => $amount,
];
}
return $out;
}
}

View File

@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
namespace app\common\service;
use support\think\Db;
/**
* 充值待支付订单超时处理:
* - 同用户最多允许 3 笔待支付订单
* - 待支付订单创建后 60 秒未支付,自动标记为失败并写失败原因
*/
final class DepositOrderExpireService
{
public const MAX_PENDING_DEPOSIT = 3;
public const EXPIRE_SECONDS = 60;
/**
* 超时失效处理。
*
* @param int|null $userId 仅处理某用户null 表示不过滤用户
* @param string|null $orderNo 仅处理某订单null 表示不过滤订单
*
* @return int 本次转失败的订单数
*/
public static function expirePendingOrders(?int $userId = null, ?string $orderNo = null): int
{
$expireBefore = time() - self::EXPIRE_SECONDS;
$query = Db::name('deposit_order')
->where('status', 0)
->where('create_time', '<=', $expireBefore);
if ($userId !== null && $userId > 0) {
$query->where('user_id', $userId);
}
if ($orderNo !== null && $orderNo !== '') {
$query->where('order_no', $orderNo);
}
$rows = $query->field(['id', 'remark'])->select()->toArray();
if ($rows === []) {
return 0;
}
$now = time();
$affectedCount = 0;
foreach ($rows as $row) {
$id = isset($row['id']) && is_numeric($row['id']) ? intval($row['id']) : 0;
if ($id <= 0) {
continue;
}
$oldRemark = isset($row['remark']) && is_string($row['remark']) ? trim($row['remark']) : '';
$reason = '[timeout] unpaid over ' . self::EXPIRE_SECONDS . 's';
$remark = $oldRemark === '' ? $reason : mb_substr($oldRemark . ' | ' . $reason, 0, 255);
$affected = Db::name('deposit_order')
->where('id', $id)
->where('status', 0)
->update([
'status' => 2,
'remark' => $remark,
'update_time' => $now,
]);
if (is_numeric($affected) && intval($affected) > 0) {
$affectedCount++;
}
}
return $affectedCount;
}
public static function pendingCountByUserId(int $userId): int
{
if ($userId <= 0) {
return 0;
}
return Db::name('deposit_order')
->where('user_id', $userId)
->where('status', 0)
->count();
}
}

View File

@@ -59,7 +59,7 @@ final class GameBetSettleService
}
$win = self::computeWinAmount($bet, $resultNumber);
$jackpot = '0.0000';
$jackpot = '0.00';
$affected = Db::name('bet_order')
->where('id', $betId)
@@ -78,10 +78,10 @@ final class GameBetSettleService
self::creditUserBetFlow($bet, $now);
if ($userId > 0) {
if (bccomp($win, '0', 4) > 0) {
if (bccomp($win, '0', 2) > 0) {
$userOutcome[$userId]['had_win'] = true;
}
if (bccomp($win, '0', 4) > 0 && StreakWinReward::isJackpotForStreakAtBet((int) ($bet['streak_at_bet'] ?? 0))) {
if (bccomp($win, '0', 2) > 0 && StreakWinReward::isJackpotForStreakAtBet((int) ($bet['streak_at_bet'] ?? 0))) {
$jackpotNotify[$userId] = true;
}
}
@@ -91,7 +91,7 @@ final class GameBetSettleService
}
$balanceAfter = (string) (Db::name('user')->where('id', $userId)->value('coin') ?? '0');
if (bccomp($win, '0', 4) > 0) {
if (bccomp($win, '0', 2) > 0) {
$paid = self::creditUserPayout($bet, $betId, $win, $now);
if ($paid !== null) {
$balanceAfter = $paid;
@@ -102,17 +102,17 @@ final class GameBetSettleService
if (!isset($aggregateByUser[$userId])) {
$aggregateByUser[$userId] = [
'period_no' => $periodNo,
'total_win' => '0.0000',
'total_win' => '0.00',
'balance_after' => $balanceAfter,
'orders' => [],
];
}
$aggregateByUser[$userId]['total_win'] = bcadd($aggregateByUser[$userId]['total_win'], $win, 4);
$aggregateByUser[$userId]['total_win'] = bcadd($aggregateByUser[$userId]['total_win'], $win, 2);
$aggregateByUser[$userId]['balance_after'] = $balanceAfter;
$aggregateByUser[$userId]['orders'][] = [
'order_no' => (string) $betId,
'win_amount' => $win,
'hit' => bccomp($win, '0', 4) > 0,
'hit' => bccomp($win, '0', 2) > 0,
];
}
@@ -150,7 +150,7 @@ final class GameBetSettleService
'balance_after' => $agg['balance_after'],
]);
if (bccomp($agg['total_win'], '0', 4) > 0) {
if (bccomp($agg['total_win'], '0', 2) > 0) {
UserPushService::publish((int) $userId, UserPushService::EVT_WALLET_CHANGED, [
'reason' => 'payout',
'ref_type' => 'game_period',
@@ -167,7 +167,7 @@ final class GameBetSettleService
continue;
}
$agg = $aggregateByUser[$uid];
if (bccomp($agg['total_win'], '0', 4) <= 0) {
if (bccomp($agg['total_win'], '0', 2) <= 0) {
continue;
}
$jackpotHits[] = [
@@ -187,7 +187,7 @@ final class GameBetSettleService
public static function settlePendingForEndedRecords(): int
{
$rows = Db::name('game_record')
->where('status', 4)
->where('status', 2)
->whereNotNull('result_number')
->field(['id', 'result_number'])
->order('id', 'asc')
@@ -237,13 +237,13 @@ final class GameBetSettleService
$pickNumbers = [];
}
if (!in_array($resultNumber, array_map('intval', $pickNumbers), true)) {
return '0.0000';
return '0.00';
}
$total = (string) ($bet['total_amount'] ?? '0');
$streak = (int) ($bet['streak_at_bet'] ?? 0);
$odds = StreakWinReward::totalOddsMultiplierForStreakAtBet($streak);
return bcmul($total, $odds, 4);
return bcmul($total, $odds, 2);
}
/**
@@ -263,8 +263,8 @@ final class GameBetSettleService
if ($total === '' || !is_numeric($total)) {
return;
}
$flow = bcadd($total, '0', 4);
if (bccomp($flow, '0', 4) <= 0) {
$flow = bcadd($total, '0', 2);
if (bccomp($flow, '0', 2) <= 0) {
return;
}
Db::name('user')
@@ -299,7 +299,7 @@ final class GameBetSettleService
}
$before = (string) ($user['coin'] ?? '0');
$after = bcadd($before, $winAmount, 4);
$after = bcadd($before, $winAmount, 2);
Db::name('user_wallet_record')->insert([
'user_id' => $userId,

View File

@@ -207,12 +207,12 @@ final class GameLiveService
for ($n = 1; $n <= self::DRAW_NUMBER_MAX; $n++) {
$loss = self::estimateLossForNumber($bets, $n);
$candidates[] = ['number' => $n, 'estimated_loss' => $loss];
if ($bestLoss === null || bccomp((string) $loss, (string) $bestLoss, 4) < 0) {
if ($bestLoss === null || bccomp((string) $loss, (string) $bestLoss, 2) < 0) {
$bestLoss = $loss;
$bestNumbers = [$n];
continue;
}
if (bccomp((string) $loss, (string) $bestLoss, 4) === 0) {
if (bccomp((string) $loss, (string) $bestLoss, 2) === 0) {
$bestNumbers[] = $n;
}
}
@@ -225,7 +225,7 @@ final class GameLiveService
}
$finalNumber = $manualNumber ?? $bestNumber;
$finalLoss = '0.0000';
$finalLoss = '0.00';
if ($finalNumber !== null) {
$finalLoss = self::estimateLossForNumber($bets, $finalNumber);
}
@@ -558,7 +558,7 @@ final class GameLiveService
if ($betId <= 0) {
continue;
}
if ($userId <= 0 || bccomp($total, '0', 4) <= 0) {
if ($userId <= 0 || bccomp($total, '0', 2) <= 0) {
Db::name('bet_order')->where('id', $betId)->where('status', 1)->update([
'status' => 3,
'update_time' => $now,
@@ -566,7 +566,7 @@ final class GameLiveService
continue;
}
$before = (string) (Db::name('user')->where('id', $userId)->value('coin') ?? '0');
$after = bcadd($before, $total, 4);
$after = bcadd($before, $total, 2);
$u = Db::name('user')->where('id', $userId)->where('coin', $before)->update([
'coin' => $after,
'update_time' => $now,
@@ -836,12 +836,12 @@ final class GameLiveService
$bestNumbers = [];
for ($n = 1; $n <= self::DRAW_NUMBER_MAX; $n++) {
$loss = self::estimateLossForNumber($bets, $n);
if ($bestLoss === null || bccomp((string) $loss, (string) $bestLoss, 4) < 0) {
if ($bestLoss === null || bccomp((string) $loss, (string) $bestLoss, 2) < 0) {
$bestLoss = $loss;
$bestNumbers = [$n];
continue;
}
if (bccomp((string) $loss, (string) $bestLoss, 4) === 0) {
if (bccomp((string) $loss, (string) $bestLoss, 2) === 0) {
$bestNumbers[] = $n;
}
}
@@ -878,7 +878,7 @@ final class GameLiveService
private static function estimateLossForNumber(array $bets, int $number): string
{
$payout = '0.0000';
$payout = '0.00';
foreach ($bets as $bet) {
$pickNumbers = $bet['pick_numbers'];
if (is_string($pickNumbers)) {
@@ -894,8 +894,8 @@ final class GameLiveService
$total = (string) ($bet['total_amount'] ?? '0');
$streak = (int) ($bet['streak_at_bet'] ?? 0);
$odds = StreakWinReward::totalOddsMultiplierForStreakAtBet($streak);
$orderPayout = bcmul($total, $odds, 4);
$payout = bcadd($payout, $orderPayout, 4);
$orderPayout = bcmul($total, $odds, 2);
$payout = bcadd($payout, $orderPayout, 2);
}
return $payout;
}

View File

@@ -29,7 +29,7 @@ final class GameRecordStatService
if ($status !== 4) {
Db::name('game_record')->where('id', $recordId)->update([
'platform_profit_amount' => '0.0000',
'platform_profit_amount' => '0.00',
'winner_user_count' => 0,
'update_time' => $now,
]);
@@ -45,8 +45,8 @@ final class GameRecordStatService
$resultNum = (int) $resultRaw;
$bets = Db::name('bet_order')->where('period_id', $recordId)->select()->toArray();
$totalBet = '0.0000';
$totalPayout = '0.0000';
$totalBet = '0.00';
$totalPayout = '0.00';
$winnerUserIds = [];
foreach ($bets as $bet) {
@@ -55,16 +55,16 @@ final class GameRecordStatService
continue;
}
$tb = (string) ($bet['total_amount'] ?? '0');
$totalBet = bcadd($totalBet, $tb, 4);
$totalBet = bcadd($totalBet, $tb, 2);
if ($st === 2) {
$payout = bcadd((string) ($bet['win_amount'] ?? '0'), (string) ($bet['jackpot_extra_amount'] ?? '0'), 4);
$payout = bcadd((string) ($bet['win_amount'] ?? '0'), (string) ($bet['jackpot_extra_amount'] ?? '0'), 2);
} else {
$payout = self::estimatePayoutForBet($bet, $resultNum);
}
$totalPayout = bcadd($totalPayout, $payout, 4);
if (bccomp($payout, '0', 4) > 0) {
$totalPayout = bcadd($totalPayout, $payout, 2);
if (bccomp($payout, '0', 2) > 0) {
$uid = (int) ($bet['user_id'] ?? 0);
if ($uid > 0) {
$winnerUserIds[$uid] = true;
@@ -72,7 +72,7 @@ final class GameRecordStatService
}
}
$profit = bcsub($totalBet, $totalPayout, 4);
$profit = bcsub($totalBet, $totalPayout, 2);
Db::name('game_record')->where('id', $recordId)->update([
'platform_profit_amount' => $profit,
@@ -96,12 +96,12 @@ final class GameRecordStatService
$pickNumbers = [];
}
if (!in_array($resultNumber, array_map('intval', $pickNumbers), true)) {
return '0.0000';
return '0.00';
}
$total = (string) ($bet['total_amount'] ?? '0');
$streak = (int) ($bet['streak_at_bet'] ?? 0);
$odds = StreakWinReward::totalOddsMultiplierForStreakAtBet($streak);
return bcmul($total, $odds, 4);
return bcmul($total, $odds, 2);
}
}

View File

@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace app\process;
use app\common\service\ChannelSettlementService;
use Workerman\Timer;
/**
* 渠道周期自动结算(每 60 秒扫描一次)
*/
class ChannelAutoSettleTicker
{
public function onWorkerStart(): void
{
Timer::add(60, static function (): void {
ChannelSettlementService::settleAllDueChannels(0);
});
}
}

View File

@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace app\process;
use app\common\service\DepositOrderExpireService;
use Workerman\Timer;
/**
* 每 10 秒扫描一次待支付充值单,把超时未支付订单自动标记为失败。
*/
class DepositOrderExpireTicker
{
public function onWorkerStart(): void
{
Timer::add(10, static function (): void {
DepositOrderExpireService::expirePendingOrders(null, null);
});
}
}

View File

@@ -15,6 +15,13 @@
use support\Request;
return [
/**
* 模拟充值网关 HMAC 密钥;生产环境请设置环境变量 DEPOSIT_MOCK_HMAC_KEY 覆盖。
* 与 app\common\library\finance\DepositMockGateway 使用。
*/
'deposit_mock_hmac_key' => is_string(getenv('DEPOSIT_MOCK_HMAC_KEY')) && trim((string) getenv('DEPOSIT_MOCK_HMAC_KEY')) !== ''
? trim((string) getenv('DEPOSIT_MOCK_HMAC_KEY'))
: '',
'debug' => true,
'error_reporting' => E_ALL,
'default_timezone' => 'Asia/Shanghai',

View File

@@ -52,6 +52,18 @@ return [
'count' => 1,
'reloadable' => false,
],
// 充值订单:超时未支付自动失败(每 10 秒扫描一次)
'depositOrderExpireTicker' => [
'handler' => app\process\DepositOrderExpireTicker::class,
'count' => 1,
'reloadable' => false,
],
// 渠道结算:按渠道周期自动结算(超管逻辑)
'channelAutoSettleTicker' => [
'handler' => app\process\ChannelAutoSettleTicker::class,
'count' => 1,
'reloadable' => false,
],
// File update detection and automatic reload
'monitor' => [

View File

@@ -137,9 +137,12 @@ Route::add(['GET', 'POST'], '/api/wallet/recordList', [\app\api\controller\Walle
Route::add(['GET', 'POST'], '/api/finance/depositTierList', [\app\api\controller\Finance::class, 'depositTierList']);
Route::post('/api/finance/depositCreate', [\app\api\controller\Finance::class, 'depositCreate']);
Route::get('/api/finance/depositMockPayPage', [\app\api\controller\Finance::class, 'depositMockPayPage']);
Route::post('/api/finance/depositMockNotify', [\app\api\controller\Finance::class, 'depositMockNotify']);
Route::add(['GET', 'POST'], '/api/finance/depositDetail', [\app\api\controller\Finance::class, 'depositDetail']);
Route::add(['GET', 'POST'], '/api/finance/depositList', [\app\api\controller\Finance::class, 'depositList']);
Route::add(['GET', 'POST'], '/api/finance/cashierConfig', [\app\api\controller\Finance::class, 'cashierConfig']);
Route::add(['GET', 'POST'], '/api/finance/depositWithdrawConfig', [\app\api\controller\Finance::class, 'depositWithdrawConfig']);
Route::post('/api/finance/withdrawCreate', [\app\api\controller\Finance::class, 'withdrawCreate']);
Route::add(['GET', 'POST'], '/api/finance/withdrawDetail', [\app\api\controller\Finance::class, 'withdrawDetail']);
Route::add(['GET', 'POST'], '/api/finance/withdrawList', [\app\api\controller\Finance::class, 'withdrawList']);
@@ -262,6 +265,9 @@ Route::get('/admin/security/dataRecycleLog/index', [\app\admin\controller\securi
Route::post('/admin/security/dataRecycleLog/restore', [\app\admin\controller\security\DataRecycleLog::class, 'restore']);
Route::get('/admin/security/dataRecycleLog/info', [\app\admin\controller\security\DataRecycleLog::class, 'info']);
// admin/config/depositTier
Route::get('/admin/config/depositTier/currencyOptions', [\app\admin\controller\config\DepositTier::class, 'currencyOptions']);
// ==================== CRUD 生成的根级控制器(/admin/item/index 或 /admin/Item/index无子目录、无点号 ====================
// 显式路由在上,此处作为兜底;与 /admin/module.controller/action 互补
Route::add(

View File

@@ -6,6 +6,9 @@ export const actionUrl = new Map([
['index', url + 'index'],
['edit', url + 'edit'],
['log', '/admin/auth.AdminLog/index'],
['walletSummary', url + 'walletSummary'],
['walletRecords', url + 'walletRecords'],
['withdrawApply', url + 'withdrawApply'],
])
export function index() {
@@ -35,3 +38,31 @@ export function postData(data: anyObj) {
}
)
}
export function walletSummary() {
return createAxios({
url: actionUrl.get('walletSummary'),
method: 'get',
})
}
export function walletRecords(filter: anyObj = {}) {
return createAxios<TableDefaultData>({
url: actionUrl.get('walletRecords'),
method: 'get',
params: filter,
})
}
export function withdrawApply(data: anyObj) {
return createAxios(
{
url: actionUrl.get('withdrawApply'),
method: 'post',
data,
},
{
showSuccessMessage: true,
}
)
}

View File

@@ -36,7 +36,7 @@ export default {
affiliate_effective_start_at: 'affiliate_effective_start_at',
affiliate_effective_end_at: 'affiliate_effective_end_at',
affiliate_ladder_rules: 'affiliate_ladder_rules',
affiliate_ladder_rules_placeholder: 'Input JSON, e.g. [{\"minLoss\":\"0.0000\",\"shareRate\":\"0.200000\"}]',
affiliate_ladder_rules_placeholder: 'Input JSON, e.g. [{\"minLoss\":\"0.00\",\"shareRate\":\"0.200000\"}]',
ladder_min_loss: 'min loss',
ladder_share_rate: 'share rate',
ladder_rule_required: 'At least one ladder rule is required',
@@ -77,6 +77,16 @@ export default {
share_rate_percent: 'Share rate(%)',
share_total_enabled: 'Enabled total',
share_total_must_100: 'Enabled share total must equal 100%',
batch_settle_pending: 'Batch settle pending channels',
settle_stats_channel_total: 'Total channels',
settle_stats_enabled: 'Enabled channels',
settle_stats_pending_dividend: 'Channels pending dividend',
settle_stats_pending_amount: 'Pending dividend amount',
settle_filter_all: 'All',
settle_filter_with_balance: 'With dividend balance',
settle_filter_no_balance: 'No dividend balance',
settle_filter_enabled: 'Enabled only',
settle_filter_disabled: 'Disabled only',
admin_id_placeholder: 'Select an admin (within your permission scope)',
admin__username: 'Person in charge',
admin_group_names: 'Role group',

View File

@@ -1,5 +1,5 @@
export default {
desc: 'Mobile pay & receipt settings: platform coin labels, currencies and rates, deposit pay channels (on/off, sort, tier scope), withdraw banks, limits, copy, and required withdraw fields. Deposit tiers are configured separately.',
desc: 'Mobile pay & receipt settings: platform coin labels, currencies and rates, deposit pay channels (on/off and sort; all tiers are supported automatically), withdraw banks, limits, copy, and required withdraw fields.',
btn_save: 'Save',
btn_add_row: 'Add row',
sec_platform: 'Platform coin labels',
@@ -7,7 +7,7 @@ export default {
platform_label_en: 'Label (English)',
sec_currencies: 'Currencies (deposit/withdraw selectors)',
sec_deposit_channels: 'Deposit pay channels',
deposit_channels_hint: 'Display names come from the registry; here you only set enabled state, sort order, and applicable deposit tiers. Leave tiers empty to allow all tiers.',
deposit_channels_hint: 'Display names come from the registry; here you only set enabled state and sort order. All enabled channels automatically support all deposit tiers.',
currency_rates_hint: 'Deposit rate: platform coins credited per 1 fiat paid. Withdraw rate: platform coins needed per 1 fiat redeemed (e.g. 100 ⇒ 100 coins = 1 fiat unit).',
err_dup_code: 'Duplicate currency codes are not allowed.',
sec_banks: 'Withdraw bank codes',
@@ -45,6 +45,4 @@ export default {
ch_display_name: 'Display name',
ch_sort: 'Sort',
ch_status: 'Enabled',
ch_tier_ids: 'Allowed deposit tiers',
ch_tier_ids_ph: 'Empty = all tiers',
}

View File

@@ -0,0 +1,37 @@
export default {
'quick Search Fields': 'Order no., receive account, remark',
id: 'ID',
order_no: 'Order No.',
admin_username: 'Admin',
channel_name: 'Channel',
amount: 'Apply amount',
actual_amount: 'Actual amount',
status: 'Status',
'status 0': 'Pending review',
'status 1': 'Approved',
'status 2': 'Rejected',
receive_type: 'Receive type',
receive_account: 'Receive account',
review_admin_username: 'Reviewer',
remark: 'Remark',
create_time: 'Create time',
review_btn_approve: 'Approve',
review_btn_reject: 'Reject',
review_approve_title: 'Approve order',
review_reject_title: 'Reject order',
review_remark_optional: 'Optional review remark',
reject_reason_required: 'Please enter reject reason',
stat_total_count: 'Total orders',
stat_pending_count: 'Pending orders',
stat_pending_amount: 'Pending amount',
stat_approved_amount: 'Approved amount',
filter_all: 'All',
filter_pending: 'Pending',
filter_approved: 'Approved',
filter_rejected: 'Rejected',
filter_receive_type_all: 'All receive types',
receive_type_bank: 'Bank card',
receive_type_ewallet: 'E-wallet',
receive_type_crypto: 'Crypto address',
}

View File

@@ -1,3 +0,0 @@
export default {
'quick Search Fields': 'order no / pay channel / tier id / idempotency key',
}

View File

@@ -7,6 +7,9 @@ export default {
amount: 'Apply amount',
fee: 'Fee',
actual_amount: 'Actual amount',
receive_type: 'Receive type',
receive_account: 'Receive account',
idempotency_key: 'Idempotency key',
status: 'Status',
'status 0': 'Pending review',
'status 1': 'Approved',

View File

@@ -11,4 +11,30 @@ export default {
'Please leave blank if not modified': 'Please leave blank if you do not modify',
'Save changes': 'Save changes',
'Operation log': 'Operation log',
admin_wallet: 'Admin wallet',
withdraw: 'Withdraw',
wallet_balance: 'Available balance',
wallet_frozen_balance: 'Frozen balance',
wallet_total_income: 'Total income',
wallet_total_withdraw: 'Total withdraw',
wallet_records: 'Wallet records',
wallet_records_type: 'Type',
wallet_records_direction: 'Direction',
wallet_direction_in: 'In',
wallet_direction_out: 'Out',
wallet_records_amount: 'Amount',
wallet_records_balance_after: 'Balance after',
wallet_records_remark: 'Remark',
wallet_records_time: 'Time',
withdraw_apply_title: 'Admin withdraw apply',
withdraw_coin: 'Withdraw amount',
withdraw_coin_placeholder: 'Please input withdraw_coin (2 decimals)',
receive_type: 'Receive type',
receive_type_placeholder: 'Please select receive_type',
receive_account: 'Receive account',
receive_account_placeholder: 'Please input receive_account',
idempotency_key: 'Idempotency key',
idempotency_key_placeholder: 'Please input idempotency_key (optional, auto-generated if empty)',
remark: 'Remark',
submit_apply: 'Submit apply',
}

View File

@@ -36,7 +36,7 @@ export default {
affiliate_effective_start_at: '联营生效开始',
affiliate_effective_end_at: '联营生效结束',
affiliate_ladder_rules: '联营阶梯规则',
affiliate_ladder_rules_placeholder: '请输入 JSON例如 [{\"minLoss\":\"0.0000\",\"shareRate\":\"0.200000\"}]',
affiliate_ladder_rules_placeholder: '请输入 JSON例如 [{\"minLoss\":\"0.00\",\"shareRate\":\"0.200000\"}]',
ladder_min_loss: '起始客损',
ladder_share_rate: '占成比例',
ladder_rule_required: '联营阶梯规则至少需要一条',
@@ -77,6 +77,16 @@ export default {
share_rate_percent: '分配比例(%)',
share_total_enabled: '启用项合计',
share_total_must_100: '启用项分配比例总和必须等于100%',
batch_settle_pending: '一键批量结算待结算渠道',
settle_stats_channel_total: '渠道总数',
settle_stats_enabled: '启用渠道',
settle_stats_pending_dividend: '待分红渠道',
settle_stats_pending_amount: '待分红总额',
settle_filter_all: '全部',
settle_filter_with_balance: '有分红余额',
settle_filter_no_balance: '无分红余额',
settle_filter_enabled: '仅启用',
settle_filter_disabled: '仅停用',
admin_id_placeholder: '请选择管理员(仅当前权限范围内)',
admin__username: '负责人',
admin_group_names: '角色组',

View File

@@ -1,5 +1,5 @@
export default {
desc: '配置移动端支付与收款展示:平台币名称、货币与汇率、充值支付渠道(开关/排序/适用档位)、提现银行、最低限额、文案与提现表单字段。充值档位在「充值档位」中维护。',
desc: '配置移动端支付与收款展示:平台币名称、货币与汇率、充值支付渠道(开关/排序,自动兼容全部档位)、提现银行、最低限额、文案与提现表单字段。',
btn_save: '保存',
btn_add_row: '新增一行',
sec_platform: '平台币展示名',
@@ -7,7 +7,7 @@ export default {
platform_label_en: '名称(英文)',
sec_currencies: '货币列表(充值/提现货币下拉)',
sec_deposit_channels: '充值支付渠道',
deposit_channels_hint: '展示名由环境注册表决定,此处仅维护启用状态排序与适用充值档位;不选档位表示全部档位可用。',
deposit_channels_hint: '展示名由环境注册表决定,此处仅维护启用状态排序;所有启用渠道自动兼容全部充值档位。',
currency_rates_hint: '充值汇率:每支付 1 单位该货币到账的平台币;提现汇率:每兑换 1 单位该货币所需平台币(例 100 表示 100 平台币 = 1 单位)。',
err_dup_code: '货币代码不能重复,请检查后再保存。',
sec_banks: '提现支持银行代码',
@@ -46,6 +46,4 @@ export default {
ch_display_name: '展示名称',
ch_sort: '排序',
ch_status: '启用',
ch_tier_ids: '适用充值档位',
ch_tier_ids_ph: '不选表示全部档位',
}

View File

@@ -0,0 +1,37 @@
export default {
'quick Search Fields': '订单号、收款账户、备注',
id: 'ID',
order_no: '订单号',
admin_username: '管理员',
channel_name: '渠道',
amount: '申请金额',
actual_amount: '实际金额',
status: '状态',
'status 0': '待审核',
'status 1': '已通过',
'status 2': '已拒绝',
receive_type: '收款方式',
receive_account: '收款账户',
review_admin_username: '审核人',
remark: '备注',
create_time: '创建时间',
review_btn_approve: '通过',
review_btn_reject: '拒绝',
review_approve_title: '通过审核',
review_reject_title: '拒绝审核',
review_remark_optional: '可选填写审核备注',
reject_reason_required: '请填写拒绝原因',
stat_total_count: '提现总单数',
stat_pending_count: '待审核单数',
stat_pending_amount: '待审核金额',
stat_approved_amount: '已通过金额',
filter_all: '全部',
filter_pending: '待审核',
filter_approved: '已通过',
filter_rejected: '已拒绝',
filter_receive_type_all: '全部收款方式',
receive_type_bank: '银行卡',
receive_type_ewallet: '电子钱包',
receive_type_crypto: '加密地址',
}

View File

@@ -1,3 +0,0 @@
export default {
'quick Search Fields': '订单号/支付通道/档位ID/幂等键',
}

View File

@@ -7,6 +7,9 @@ export default {
amount: '申请金额',
fee: '手续费',
actual_amount: '实际到账',
receive_type: '收款类型',
receive_account: '收款账号',
idempotency_key: '幂等键',
status: '状态',
'status 0': '待审核',
'status 1': '已通过',

View File

@@ -11,4 +11,30 @@ export default {
'Please leave blank if not modified': '不修改请留空',
'Save changes': '保存修改',
'Operation log': '操作日志',
admin_wallet: '管理员钱包',
withdraw: '提现',
wallet_balance: '可用余额',
wallet_frozen_balance: '冻结余额',
wallet_total_income: '累计入账',
wallet_total_withdraw: '累计提现',
wallet_records: '钱包流水',
wallet_records_type: '类型',
wallet_records_direction: '方向',
wallet_direction_in: '入账',
wallet_direction_out: '出账',
wallet_records_amount: '金额',
wallet_records_balance_after: '变动后余额',
wallet_records_remark: '备注',
wallet_records_time: '时间',
withdraw_apply_title: '管理员提现申请',
withdraw_coin: '提现金额',
withdraw_coin_placeholder: '请输入 withdraw_coin两位小数',
receive_type: '收款方式',
receive_type_placeholder: '请选择 receive_type',
receive_account: '收款账户',
receive_account_placeholder: '请输入 receive_account',
idempotency_key: '幂等键',
idempotency_key_placeholder: '请输入 idempotency_key可留空自动生成',
remark: '备注',
submit_apply: '提交申请',
}

View File

@@ -30,6 +30,17 @@ const { t } = useI18n()
const tableRef = useTemplateRef('tableRef')
const optButtons: OptButton[] = defaultOptButtons(['edit', 'delete'])
function formatAmount2(_row: anyObj, _column: any, cellValue: unknown) {
if (cellValue === null || cellValue === undefined || cellValue === '') {
return '-'
}
const n = Number(cellValue)
if (!Number.isFinite(n)) {
return String(cellValue)
}
return n.toFixed(2)
}
const baTable = new baTableClass(
new baTableApi('/admin/agent.CommissionRecord/'),
{
@@ -74,9 +85,30 @@ const baTable = new baTableClass(
operatorPlaceholder: t('Fuzzy query'),
render: 'tags',
},
{ label: t('agent.commissionRecord.commission_rate'), prop: 'commission_rate', align: 'center', minWidth: 110, operator: 'RANGE' },
{ label: t('agent.commissionRecord.calc_base_amount'), prop: 'calc_base_amount', align: 'center', minWidth: 120, operator: 'RANGE' },
{ label: t('agent.commissionRecord.commission_amount'), prop: 'commission_amount', align: 'center', minWidth: 120, operator: 'RANGE' },
{
label: t('agent.commissionRecord.commission_rate'),
prop: 'commission_rate',
align: 'center',
minWidth: 110,
operator: 'RANGE',
formatter: formatAmount2,
},
{
label: t('agent.commissionRecord.calc_base_amount'),
prop: 'calc_base_amount',
align: 'center',
minWidth: 120,
operator: 'RANGE',
formatter: formatAmount2,
},
{
label: t('agent.commissionRecord.commission_amount'),
prop: 'commission_amount',
align: 'center',
minWidth: 120,
operator: 'RANGE',
formatter: formatAmount2,
},
{
label: t('agent.commissionRecord.status'),
prop: 'status',
@@ -138,7 +170,7 @@ const baTable = new baTableClass(
],
},
{
defaultItems: { status: 0, commission_rate: '0.0000' },
defaultItems: { status: 0, commission_rate: '0.00' },
}
)

View File

@@ -45,9 +45,9 @@
placeholder: t('Click select'),
}"
/>
<FormItem :label="t('agent.commissionRecord.commission_rate')" type="number" v-model="baTable.form.items!.commission_rate" prop="commission_rate" :input-attr="{ min: 0, precision: 4, step: 0.0001 }" />
<FormItem :label="t('agent.commissionRecord.calc_base_amount')" type="number" v-model="baTable.form.items!.calc_base_amount" prop="calc_base_amount" :input-attr="{ min: 0, precision: 4, step: 0.0001 }" />
<FormItem :label="t('agent.commissionRecord.commission_amount')" type="number" v-model="baTable.form.items!.commission_amount" prop="commission_amount" :input-attr="{ precision: 4, step: 0.0001 }" />
<FormItem :label="t('agent.commissionRecord.commission_rate')" type="number" v-model="baTable.form.items!.commission_rate" prop="commission_rate" :input-attr="{ min: 0, precision: 2, step: 0.01 }" />
<FormItem :label="t('agent.commissionRecord.calc_base_amount')" type="number" v-model="baTable.form.items!.calc_base_amount" prop="calc_base_amount" :input-attr="{ min: 0, precision: 2, step: 0.01 }" />
<FormItem :label="t('agent.commissionRecord.commission_amount')" type="number" v-model="baTable.form.items!.commission_amount" prop="commission_amount" :input-attr="{ precision: 2, step: 0.01 }" />
<FormItem :label="t('agent.commissionRecord.status')" type="radio" v-model="baTable.form.items!.status" prop="status" :input-attr="{ content: { '0': t('agent.commissionRecord.status 0'), '1': t('agent.commissionRecord.status 1'), '2': t('agent.commissionRecord.status 2') } }" />
<FormItem :label="t('agent.commissionRecord.settled_at')" type="datetime" v-model="baTable.form.items!.settled_at" prop="settled_at" />
<FormItem :label="t('agent.commissionRecord.remark')" type="textarea" v-model="baTable.form.items!.remark" prop="remark" :input-attr="{ rows: 2 }" />

View File

@@ -30,6 +30,17 @@ const { t } = useI18n()
const tableRef = useTemplateRef('tableRef')
const optButtons: OptButton[] = defaultOptButtons(['edit', 'delete'])
function formatAmount2(_row: anyObj, _column: any, cellValue: unknown) {
if (cellValue === null || cellValue === undefined || cellValue === '') {
return '-'
}
const n = Number(cellValue)
if (!Number.isFinite(n)) {
return String(cellValue)
}
return n.toFixed(2)
}
const baTable = new baTableClass(
new baTableApi('/admin/agent.SettlementPeriod/'),
{
@@ -67,13 +78,21 @@ const baTable = new baTableClass(
sortable: 'custom',
timeFormat: 'yyyy-mm-dd hh:MM:ss',
},
{ label: t('agent.settlementPeriod.total_bet_amount'), prop: 'total_bet_amount', align: 'center', operator: 'RANGE', minWidth: 120 },
{
label: t('agent.settlementPeriod.total_bet_amount'),
prop: 'total_bet_amount',
align: 'center',
operator: 'RANGE',
minWidth: 120,
formatter: formatAmount2,
},
{
label: t('agent.settlementPeriod.total_payout_amount'),
prop: 'total_payout_amount',
align: 'center',
operator: 'RANGE',
minWidth: 120,
formatter: formatAmount2,
},
{
label: t('agent.settlementPeriod.platform_profit_amount'),
@@ -81,6 +100,7 @@ const baTable = new baTableClass(
align: 'center',
operator: 'RANGE',
minWidth: 120,
formatter: formatAmount2,
},
{
label: t('agent.settlementPeriod.status'),

View File

@@ -9,9 +9,9 @@
<FormItem :label="t('agent.settlementPeriod.settlement_no')" type="string" v-model="baTable.form.items!.settlement_no" prop="settlement_no" />
<FormItem :label="t('agent.settlementPeriod.period_start_at')" type="datetime" v-model="baTable.form.items!.period_start_at" prop="period_start_at" />
<FormItem :label="t('agent.settlementPeriod.period_end_at')" type="datetime" v-model="baTable.form.items!.period_end_at" prop="period_end_at" />
<FormItem :label="t('agent.settlementPeriod.total_bet_amount')" type="number" v-model="baTable.form.items!.total_bet_amount" prop="total_bet_amount" :input-attr="{ min: 0, precision: 4, step: 0.0001 }" />
<FormItem :label="t('agent.settlementPeriod.total_payout_amount')" type="number" v-model="baTable.form.items!.total_payout_amount" prop="total_payout_amount" :input-attr="{ min: 0, precision: 4, step: 0.0001 }" />
<FormItem :label="t('agent.settlementPeriod.platform_profit_amount')" type="number" v-model="baTable.form.items!.platform_profit_amount" prop="platform_profit_amount" :input-attr="{ precision: 4, step: 0.0001 }" />
<FormItem :label="t('agent.settlementPeriod.total_bet_amount')" type="number" v-model="baTable.form.items!.total_bet_amount" prop="total_bet_amount" :input-attr="{ min: 0, precision: 2, step: 0.01 }" />
<FormItem :label="t('agent.settlementPeriod.total_payout_amount')" type="number" v-model="baTable.form.items!.total_payout_amount" prop="total_payout_amount" :input-attr="{ min: 0, precision: 2, step: 0.01 }" />
<FormItem :label="t('agent.settlementPeriod.platform_profit_amount')" type="number" v-model="baTable.form.items!.platform_profit_amount" prop="platform_profit_amount" :input-attr="{ precision: 2, step: 0.01 }" />
<FormItem :label="t('agent.settlementPeriod.status')" type="radio" v-model="baTable.form.items!.status" prop="status" :input-attr="{ content: { '0': t('agent.settlementPeriod.status 0'), '1': t('agent.settlementPeriod.status 1'), '2': t('agent.settlementPeriod.status 2'), '3': t('agent.settlementPeriod.status 3') } }" />
<FormItem :label="t('agent.settlementPeriod.remark')" type="textarea" v-model="baTable.form.items!.remark" prop="remark" :input-attr="{ rows: 2 }" />
</el-form>

View File

@@ -6,17 +6,55 @@
:buttons="['refresh', 'add', 'edit', 'delete', 'comSearch', 'quickSearch', 'columnDisplay']"
:quick-search-placeholder="t('Quick search placeholder', { fields: t('channel.quick Search Fields') })"
></TableHeader>
<div class="channel-top-actions">
<div class="channel-stats-cards">
<el-card shadow="never" class="channel-stat-card">
<div class="label">{{ t('channel.settle_stats_channel_total') }}</div>
<div class="value">{{ settleStats.channel_total }}</div>
</el-card>
<el-card shadow="never" class="channel-stat-card">
<div class="label">{{ t('channel.settle_stats_enabled') }}</div>
<div class="value">{{ settleStats.enabled_count }}</div>
</el-card>
<el-card shadow="never" class="channel-stat-card">
<div class="label">{{ t('channel.settle_stats_pending_dividend') }}</div>
<div class="value">{{ settleStats.carryover_positive_count }}</div>
</el-card>
<el-card shadow="never" class="channel-stat-card">
<div class="label">{{ t('channel.settle_stats_pending_amount') }}</div>
<div class="value">{{ settleStats.carryover_positive_total }}</div>
</el-card>
</div>
<div class="channel-action-row">
<el-radio-group v-model="settleFilterMode" size="small" @change="onSettleFilterChange">
<el-radio-button label="all">{{ t('channel.settle_filter_all') }}</el-radio-button>
<el-radio-button label="with_balance">{{ t('channel.settle_filter_with_balance') }}</el-radio-button>
<el-radio-button label="no_balance">{{ t('channel.settle_filter_no_balance') }}</el-radio-button>
<el-radio-button label="enabled">{{ t('channel.settle_filter_enabled') }}</el-radio-button>
<el-radio-button label="disabled">{{ t('channel.settle_filter_disabled') }}</el-radio-button>
</el-radio-group>
<el-button v-if="auth('batchSettlePending')" type="warning" @click="onBatchSettlePending">
{{ t('channel.batch_settle_pending') }}
</el-button>
</div>
</div>
<Table ref="tableRef"></Table>
<PopupForm />
<el-dialog class="ba-operate-dialog" :close-on-click-modal="false" :model-value="manualSettle.visible" @close="closeManualSettleDialog">
<el-dialog
class="ba-operate-dialog manual-settle-dialog"
:close-on-click-modal="false"
:model-value="manualSettle.visible"
width="860px"
@close="closeManualSettleDialog"
>
<template #header>
<div class="title">{{ t('channel.manual_settle') }}</div>
</template>
<div v-loading="manualSettle.previewLoading" class="manual-settle-dialog-body">
<el-form :model="manualSettle.form" label-width="140px">
<el-form :model="manualSettle.form" label-width="140px" class="manual-settle-form">
<el-form-item :label="t('channel.manual_settle_settlement_no')">
<el-input v-model="manualSettle.form.settlement_no" readonly />
</el-form-item>
@@ -44,8 +82,8 @@
<el-form-item :label="t('channel.manual_settle_commission_amount')">
<el-input v-model="manualSettle.form.commission_amount" readonly />
</el-form-item>
<el-form-item :label="t('channel.share_config')">
<el-table :data="manualSettle.form.commission_split" border size="small" class="w100">
<el-form-item :label="t('channel.share_config')" class="manual-settle-form-item-full">
<el-table :data="manualSettle.form.commission_split" border size="small" class="w100" max-height="220">
<el-table-column prop="admin_username" :label="t('channel.admin__username')" min-width="100" />
<el-table-column prop="share_rate" :label="t('channel.share_rate_percent')" min-width="90">
<template #default="scope">{{ scope.row.share_rate }}%</template>
@@ -53,16 +91,18 @@
<el-table-column prop="commission_amount" :label="t('channel.manual_settle_commission_amount')" min-width="110" />
</el-table>
</el-form-item>
<el-form-item :label="t('channel.manual_settle_remark')">
<el-form-item :label="t('channel.manual_settle_remark')" class="manual-settle-form-item-full">
<el-input v-model="manualSettle.form.remark" type="textarea" :rows="2" />
</el-form-item>
</el-form>
</div>
<template #footer>
<el-button @click="closeManualSettleDialog">{{ t('Cancel') }}</el-button>
<el-button type="primary" :disabled="manualSettle.previewLoading" :loading="manualSettle.loading" @click="submitManualSettle">
{{ t('Save') }}
</el-button>
<div class="manual-settle-footer">
<el-button @click="closeManualSettleDialog">{{ t('Cancel') }}</el-button>
<el-button type="primary" :disabled="manualSettle.previewLoading" :loading="manualSettle.loading" @click="submitManualSettle">
{{ t('Save') }}
</el-button>
</div>
</template>
</el-dialog>
@@ -115,7 +155,7 @@
</template>
<script setup lang="ts">
import { computed, onMounted, provide, reactive, useTemplateRef } from 'vue'
import { computed, onMounted, provide, reactive, ref, useTemplateRef } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
import PopupForm from './popupForm.vue'
@@ -207,6 +247,15 @@ const shareDialog = reactive({
channelId: 0,
list: [] as Array<{ admin_id: number; username: string; role_group_name: string; role_level: number; status: number; share_rate: number | null }>,
})
const settleFilterMode = ref<'all' | 'with_balance' | 'no_balance' | 'enabled' | 'disabled'>('all')
const settleStats = reactive({
channel_total: 0,
enabled_count: 0,
disabled_count: 0,
carryover_positive_count: 0,
carryover_total: '0.00',
carryover_positive_total: '0.00',
})
const shareEnabledTotal = computed(() => {
let sum = 0
@@ -370,6 +419,35 @@ const submitManualSettle = async () => {
}
}
const onBatchSettlePending = async () => {
await createAxios(
{
url: '/admin/channel/batchSettlePending',
method: 'post',
},
{ showSuccessMessage: true }
)
await loadSettleStats()
baTable.onTableHeaderAction('refresh', { event: 'batch-settle' })
}
const onSettleFilterChange = () => {
baTable.getData()
}
const loadSettleStats = async () => {
const res = await createAxios({ url: '/admin/channel/settleStats', method: 'get' })
if (res.code !== 1 || !res.data) {
return
}
settleStats.channel_total = Number(res.data.channel_total ?? 0)
settleStats.enabled_count = Number(res.data.enabled_count ?? 0)
settleStats.disabled_count = Number(res.data.disabled_count ?? 0)
settleStats.carryover_positive_count = Number(res.data.carryover_positive_count ?? 0)
settleStats.carryover_total = String(res.data.carryover_total ?? '0.00')
settleStats.carryover_positive_total = String(res.data.carryover_positive_total ?? '0.00')
}
const baTable = new baTableClass(
new baTableApi('/admin/channel/'),
{
@@ -564,6 +642,27 @@ const baTable = new baTableClass(
}
)
baTable.before.getData = () => {
const filter = baTable.table.filter || {}
const searchRaw = filter.search
const search = Array.isArray(searchRaw) ? searchRaw.filter((item: any) => item && item.field !== 'carryover_balance' && item.field !== 'status') : []
if (settleFilterMode.value === 'with_balance') {
search.push({ field: 'carryover_balance', operator: 'gt', val: 0 })
} else if (settleFilterMode.value === 'no_balance') {
search.push({ field: 'carryover_balance', operator: 'elt', val: 0 })
} else if (settleFilterMode.value === 'enabled') {
search.push({ field: 'status', operator: 'eq', val: 1 })
} else if (settleFilterMode.value === 'disabled') {
search.push({ field: 'status', operator: 'eq', val: 0 })
}
filter.search = search
baTable.table.filter = filter
}
baTable.after.getData = () => {
void loadSettleStats()
}
provide('baTable', baTable)
onMounted(() => {
@@ -573,6 +672,7 @@ onMounted(() => {
baTable.initSort()
baTable.dragSort()
})
void loadSettleStats()
})
</script>
@@ -597,4 +697,71 @@ onMounted(() => {
.share-group-empty {
color: var(--el-text-color-placeholder);
}
.channel-top-actions {
margin: 8px 0 12px;
}
.channel-stats-cards {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 10px;
margin-bottom: 10px;
}
.channel-stat-card .label {
font-size: 12px;
color: var(--el-text-color-secondary);
}
.channel-stat-card .value {
margin-top: 6px;
font-size: 20px;
font-weight: 600;
color: var(--el-text-color-primary);
}
.channel-action-row {
display: flex;
justify-content: space-between;
gap: 10px;
align-items: center;
flex-wrap: wrap;
}
.manual-settle-dialog-body {
max-height: min(70vh, 680px);
overflow: auto;
padding-right: 2px;
}
.manual-settle-form {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
column-gap: 16px;
}
.manual-settle-form :deep(.el-form-item) {
margin-bottom: 12px;
}
.manual-settle-form-item-full {
grid-column: 1 / -1;
}
.manual-settle-footer {
display: flex;
justify-content: flex-end;
gap: 8px;
}
@media (max-width: 900px) {
.channel-stats-cards {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.manual-settle-form {
grid-template-columns: 1fr;
}
}
</style>

View File

@@ -91,7 +91,7 @@
type="number"
v-model="baTable.form.items!.affiliate_share_rate"
prop="affiliate_share_rate"
:input-attr="{ step: 0.000001, precision: 6, min: 0, max: 1 }"
:input-attr="{ step: 0.0001, precision: 2, min: 0, max: 1 }"
:placeholder="`${t('Please input field', { field: t('channel.affiliate_share_rate') })} (例如 0.240000)`"
/>
<FormItem
@@ -100,7 +100,7 @@
type="number"
v-model="baTable.form.items!.affiliate_fee_rate"
prop="affiliate_fee_rate"
:input-attr="{ step: 0.000001, precision: 6, min: 0, max: 1 }"
:input-attr="{ step: 0.0001, precision: 2, min: 0, max: 1 }"
:placeholder="`${t('Please input field', { field: t('channel.affiliate_fee_rate') })} (例如 0.070000)`"
/>
<el-form-item :label="t('channel.settle_cycle')" prop="settle_plan">
@@ -140,7 +140,7 @@
</div>
<div v-for="(item, idx) in ladderRuleList" :key="idx" class="ladder-rule-row">
<el-input-number v-model="item.minLoss" class="w100" :precision="4" :step="0.0001" :min="0" />
<el-input-number v-model="item.shareRate" class="w100" :precision="6" :step="0.000001" :min="0" :max="1" />
<el-input-number v-model="item.shareRate" class="w100" :precision="6" :step="0.0001" :min="0" :max="1" />
<el-button type="danger" link @click="removeLadderRule(idx)">{{ t('Delete') }}</el-button>
</div>
<el-button type="primary" link @click="addLadderRule">{{ t('Add') }}</el-button>
@@ -480,7 +480,7 @@ baTable.before.onSubmit = ({ items }) => {
}
}
items.affiliate_ladder_rules = sorted.map((r) => ({
minLoss: Number(r.minLoss).toFixed(4),
minLoss: Number(r.minLoss).toFixed(2),
shareRate: Number(r.shareRate).toFixed(6),
}))
} else {

View File

@@ -44,7 +44,6 @@ const baTable = new baTableClass(
defaultOrder: { prop: 'sort', order: 'asc' },
extend: {
registry: {} as Record<string, { name: string; name_en: string; sort: number }>,
tier_options: [] as { id: string; label: string }[],
},
column: [
{ type: 'selection', align: 'center', operator: false },
@@ -83,25 +82,6 @@ const baTable = new baTableClass(
operatorPlaceholder: t('Fuzzy query'),
showOverflowTooltip: true,
},
{
label: t('config.depositChannel.tier_ids'),
prop: 'tier_ids',
align: 'center',
minWidth: 240,
operator: false,
render: 'tags',
formatter: (row: anyObj) => {
const ids = row.tier_ids
if (!Array.isArray(ids) || ids.length === 0) {
return [t('config.depositChannel.tier_all')]
}
const opts = (baTable.table.extend?.tier_options ?? []) as { id: string; label: string }[]
return ids.map((id: string) => {
const o = opts.find((x) => x.id === id)
return o ? o.label : id
})
},
},
{
label: t('Operate'),
align: 'center',
@@ -119,7 +99,6 @@ const baTable = new baTableClass(
code: '',
sort: 10,
status: 1,
tier_ids: [] as string[],
},
},
{},
@@ -128,15 +107,11 @@ const baTable = new baTableClass(
const d = res.data as
| {
registry?: Record<string, { name: string; name_en: string; sort: number }>
tier_options?: { id: string; label: string }[]
}
| undefined
if (d?.registry) {
baTable.table.extend.registry = d.registry
}
if (d?.tier_options) {
baTable.table.extend.tier_options = d.tier_options
}
},
}
)

View File

@@ -43,20 +43,6 @@
<el-switch v-model="baTable.form.items!.status" :active-value="1" :inactive-value="0" />
</el-form-item>
<el-form-item :label="t('config.depositChannel.tier_ids')" prop="tier_ids">
<el-select
v-model="baTable.form.items!.tier_ids"
multiple
collapse-tags
collapse-tags-tooltip
filterable
clearable
class="w100"
:placeholder="t('config.depositChannel.tier_ids_ph')"
>
<el-option v-for="opt in tierOptions" :key="opt.id" :label="opt.label" :value="opt.id" />
</el-select>
</el-form-item>
</el-form>
</div>
</el-scrollbar>
@@ -77,18 +63,11 @@ import { computed, inject, useTemplateRef } from 'vue'
import { useI18n } from 'vue-i18n'
import { useConfig } from '/@/stores/config'
type TierOpt = { id: string; label: string }
const config = useConfig()
const formRef = useTemplateRef<FormInstance>('formRef')
const baTable = inject('baTable') as baTable
const { t } = useI18n()
const tierOptions = computed(() => {
const raw = baTable.table.extend?.tier_options
return Array.isArray(raw) ? (raw as TierOpt[]) : []
})
const registryDisplayName = computed(() => {
const code = String(baTable.form.items?.code ?? '')
const reg = baTable.table.extend?.registry as Record<string, { name?: string }> | undefined

View File

@@ -42,7 +42,7 @@ function formatAmount4(_row: anyObj, _column: any, cellValue: unknown) {
if (!Number.isFinite(n)) {
return String(cellValue)
}
return n.toFixed(4)
return n.toFixed(2)
}
function formatPayCell(row: anyObj, _column: any, cellValue: unknown) {
@@ -59,7 +59,7 @@ function formatTotalPlatform(row: anyObj) {
const b = parseFloat(String(row.bonus_amount ?? '0').replace(',', '.'))
const base = Number.isFinite(a) ? a : 0
const bonus = Number.isFinite(b) ? b : 0
return (base + bonus).toFixed(4)
return (base + bonus).toFixed(2)
}
const baTable = new baTableClass(
@@ -68,7 +68,7 @@ const baTable = new baTableClass(
pk: 'id',
filter: {
page: 1,
limit: 20,
limit: 100,
},
defaultOrder: { prop: 'sort', order: 'asc' },
column: [

View File

@@ -87,16 +87,37 @@
<script setup lang="ts">
import type { FormInstance, FormItemRule } from 'element-plus'
import { inject, reactive, useTemplateRef } from 'vue'
import { inject, onMounted, reactive, ref, useTemplateRef } from 'vue'
import { useI18n } from 'vue-i18n'
import { useConfig } from '/@/stores/config'
import createAxios from '/@/utils/axios'
const config = useConfig()
const formRef = useTemplateRef<FormInstance>('formRef')
const baTable = inject('baTable') as baTable
const { t } = useI18n()
const payCurrencies = ['MYR', 'CNY', 'USD', 'USDT', 'VND', 'THB', 'SGD', 'IDR']
const payCurrencies = ref<string[]>(['MYR', 'CNY', 'USD', 'USDT', 'VND', 'THB', 'SGD', 'IDR'])
async function loadPayCurrencies() {
try {
const res = await createAxios({
url: '/admin/config.DepositTier/currencyOptions',
method: 'GET',
})
const listRaw = (res as anyObj)?.data?.list
if (Array.isArray(listRaw)) {
const list = listRaw
.map((x: unknown) => (typeof x === 'string' ? x.trim().toUpperCase() : ''))
.filter((x: string) => x !== '')
if (list.length > 0) {
payCurrencies.value = Array.from(new Set(list))
}
}
} catch (_e) {
// 下拉拉取失败时保持内置兜底列表,避免阻断表单编辑
}
}
function positiveAmountRule(msg: string): FormItemRule {
return {
@@ -143,6 +164,10 @@ const rules = reactive({
amount: [positiveAmountRule(t('config.depositTier.rule_platform_base'))],
bonus_amount: [nonNegAmountRule(t('config.depositTier.rule_bonus'))],
})
onMounted(() => {
loadPayCurrencies()
})
</script>
<style scoped lang="scss">

View File

@@ -103,22 +103,6 @@
<el-switch v-model="row.status" :active-value="1" :inactive-value="0" />
</template>
</el-table-column>
<el-table-column :label="t('config.financeCashierConfig.ch_tier_ids')" min-width="220">
<template #default="{ row }">
<el-select
v-model="row.tier_ids"
multiple
collapse-tags
collapse-tags-tooltip
filterable
clearable
class="w100p"
:placeholder="t('config.financeCashierConfig.ch_tier_ids_ph')"
>
<el-option v-for="opt in tierOptions" :key="opt.id" :label="opt.label" :value="opt.id" />
</el-select>
</template>
</el-table-column>
</el-table>
</el-card>
@@ -237,13 +221,11 @@ type CurrencyRow = {
}
type BankRow = { code: string; name_zh: string; name_en: string; sort: number }
type ChannelRow = { code: string; sort: number; status: number; tier_ids: string[] }
type TierOpt = { id: string; label: string }
type RegistryMeta = { name?: string; name_en?: string; sort?: number }
const loading = ref(false)
const saving = ref(false)
const registry = ref<Record<string, RegistryMeta>>({})
const tierOptions = ref<TierOpt[]>([])
const form = reactive({
platform_coin: { label_zh: '', label_en: '' },
@@ -363,24 +345,13 @@ function channelDisplayName(code: string): string {
}
function normalizeChannelRow(c: Record<string, unknown>): ChannelRow {
const tierIds: string[] = []
if (Array.isArray(c.tier_ids)) {
for (const x of c.tier_ids) {
if (typeof x === 'string') {
const t = x.trim()
if (t !== '') {
tierIds.push(t)
}
}
}
}
const st = c.status
const statusOn = st === 1 || st === true || st === '1'
return {
code: typeof c.code === 'string' ? c.code : '',
sort: rowSortValue({ sort: c.sort }),
status: statusOn ? 1 : 0,
tier_ids: tierIds,
tier_ids: [],
}
}
@@ -406,8 +377,6 @@ async function load() {
regRaw !== null && typeof regRaw === 'object' && !Array.isArray(regRaw)
? (regRaw as Record<string, RegistryMeta>)
: {}
const topts = res.data.tier_options
tierOptions.value = Array.isArray(topts) ? (topts as TierOpt[]) : []
Object.assign(form.platform_coin, f.platform_coin || {})
const curList = Array.isArray(f.currencies) ? f.currencies : []
const normalized: CurrencyRow[] = curList.map((c: Record<string, unknown>) => ({

View File

@@ -248,7 +248,7 @@ const voidReason = ref('')
const voidSubmitting = ref(false)
const manualNumber = ref<number | null>(1)
const calcResultNumber = ref<number | null>(null)
const calcEstimatedLoss = ref<string>('0.0000')
const calcEstimatedLoss = ref<string>('0.00')
/** 服务端 Unix 秒 本地 Unix 秒,用于派彩倒计时与服务器对齐 */
const serverSkewSeconds = ref(0)
@@ -487,7 +487,7 @@ async function onCalculate() {
snapshot.candidate_numbers = res.data.candidate_numbers || []
snapshot.ai_default_number = res.data.ai_default_number ?? null
calcResultNumber.value = res.data.final_number ?? null
calcEstimatedLoss.value = String(res.data.final_estimated_loss ?? '0.0000')
calcEstimatedLoss.value = String(res.data.final_estimated_loss ?? '0.00')
}
} finally {
calcLoading.value = false

View File

@@ -35,7 +35,7 @@ const formatCoin = (_row: any, _column: any, cellValue: number | string | null |
if (cellValue === null || cellValue === undefined || cellValue === '') return '—'
const n = Number(cellValue)
if (Number.isNaN(n)) return '—'
return n.toFixed(4)
return n.toFixed(2)
}
const baTable = new baTableClass(

View File

@@ -0,0 +1,277 @@
<template>
<div class="default-main ba-table-box">
<el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info" show-icon />
<TableHeader
:buttons="['refresh', 'comSearch', 'quickSearch', 'columnDisplay']"
:quick-search-placeholder="t('Quick search placeholder', { fields: t('order.adminWithdrawOrder.quick Search Fields') })"
/>
<div class="withdraw-stats-cards">
<el-card shadow="never" class="withdraw-stat-card">
<div class="label">{{ t('order.adminWithdrawOrder.stat_total_count') }}</div>
<div class="value">{{ stats.total_count }}</div>
</el-card>
<el-card shadow="never" class="withdraw-stat-card">
<div class="label">{{ t('order.adminWithdrawOrder.stat_pending_count') }}</div>
<div class="value">{{ stats.pending_count }}</div>
</el-card>
<el-card shadow="never" class="withdraw-stat-card">
<div class="label">{{ t('order.adminWithdrawOrder.stat_pending_amount') }}</div>
<div class="value">{{ stats.pending_amount }}</div>
</el-card>
<el-card shadow="never" class="withdraw-stat-card">
<div class="label">{{ t('order.adminWithdrawOrder.stat_approved_amount') }}</div>
<div class="value">{{ stats.approved_amount }}</div>
</el-card>
</div>
<div class="withdraw-filter-row">
<el-radio-group v-model="statusFilterMode" size="small" @change="onStatusFilterChange">
<el-radio-button label="all">{{ t('order.adminWithdrawOrder.filter_all') }}</el-radio-button>
<el-radio-button label="pending">{{ t('order.adminWithdrawOrder.filter_pending') }}</el-radio-button>
<el-radio-button label="approved">{{ t('order.adminWithdrawOrder.filter_approved') }}</el-radio-button>
<el-radio-button label="rejected">{{ t('order.adminWithdrawOrder.filter_rejected') }}</el-radio-button>
</el-radio-group>
<el-select v-model="receiveTypeFilterMode" class="receive-type-filter" @change="onStatusFilterChange">
<el-option :label="t('order.adminWithdrawOrder.filter_receive_type_all')" value="all" />
<el-option :label="t('order.adminWithdrawOrder.receive_type_bank')" value="bank" />
<el-option :label="t('order.adminWithdrawOrder.receive_type_ewallet')" value="ewallet" />
<el-option :label="t('order.adminWithdrawOrder.receive_type_crypto')" value="crypto" />
</el-select>
</div>
<Table ref="tableRef"></Table>
</div>
</template>
<script setup lang="ts">
import { onMounted, provide, reactive, ref, useTemplateRef } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessageBox } from 'element-plus'
import { baTableApi } from '/@/api/common'
import TableHeader from '/@/components/table/header/index.vue'
import Table from '/@/components/table/index.vue'
import baTableClass from '/@/utils/baTable'
import createAxios from '/@/utils/axios'
defineOptions({
name: 'order/adminWithdrawOrder',
})
const { t } = useI18n()
const tableRef = useTemplateRef('tableRef')
const statusFilterMode = ref<'all' | 'pending' | 'approved' | 'rejected'>('all')
const receiveTypeFilterMode = ref<'all' | 'bank' | 'ewallet' | 'crypto'>('all')
const stats = reactive({
total_count: 0,
pending_count: 0,
approved_count: 0,
rejected_count: 0,
total_amount: '0.00',
pending_amount: '0.00',
approved_amount: '0.00',
})
const onReview = async (row: anyObj, action: 'approve' | 'reject') => {
const needReason = action === 'reject'
const { value } = await ElMessageBox.prompt(
needReason ? t('order.adminWithdrawOrder.reject_reason_required') : t('order.adminWithdrawOrder.review_remark_optional'),
action === 'approve' ? t('order.adminWithdrawOrder.review_approve_title') : t('order.adminWithdrawOrder.review_reject_title'),
{
confirmButtonText: t('Confirm'),
cancelButtonText: t('Cancel'),
inputPlaceholder: needReason ? t('order.adminWithdrawOrder.reject_reason_required') : t('order.adminWithdrawOrder.review_remark_optional'),
inputPattern: needReason ? /.+/ : undefined,
inputErrorMessage: needReason ? t('order.adminWithdrawOrder.reject_reason_required') : '',
})
await createAxios(
{
url: `/admin/order.AdminWithdrawOrder/${action}`,
method: 'post',
data: { id: row.id, remark: value || '' },
},
{ showSuccessMessage: true }
)
await loadStats()
baTable.getData()
}
const optButtons: OptButton[] = [
{
render: 'tipButton',
name: 'approve',
title: 'order.adminWithdrawOrder.review_btn_approve',
text: '',
type: 'success',
icon: 'el-icon-Check',
display: (row: TableRow) => Number(row.status) === 0,
click: (row: TableRow) => void onReview(row as anyObj, 'approve'),
},
{
render: 'tipButton',
name: 'reject',
title: 'order.adminWithdrawOrder.review_btn_reject',
text: '',
type: 'danger',
icon: 'el-icon-Close',
display: (row: TableRow) => Number(row.status) === 0,
click: (row: TableRow) => void onReview(row as anyObj, 'reject'),
},
]
const baTable = new baTableClass(
new baTableApi('/admin/order.AdminWithdrawOrder/'),
{
pk: 'id',
column: [
{ type: 'selection', align: 'center', operator: false },
{ label: t('order.adminWithdrawOrder.id'), prop: 'id', align: 'center', width: 70, operator: 'RANGE', sortable: 'custom' },
{ label: t('order.adminWithdrawOrder.order_no'), prop: 'order_no', align: 'center', minWidth: 170, operator: 'LIKE' },
{ label: t('order.adminWithdrawOrder.admin_username'), prop: 'admin.username', align: 'center', minWidth: 120, operator: 'LIKE' },
{ label: t('order.adminWithdrawOrder.channel_name'), prop: 'channel.name', align: 'center', minWidth: 120, operator: 'LIKE' },
{ label: t('order.adminWithdrawOrder.amount'), prop: 'amount', align: 'center', minWidth: 100, operator: 'RANGE' },
{ label: t('order.adminWithdrawOrder.actual_amount'), prop: 'actual_amount', align: 'center', minWidth: 100, operator: 'RANGE' },
{
label: t('order.adminWithdrawOrder.status'),
prop: 'status',
align: 'center',
operator: 'eq',
render: 'tag',
custom: { 0: 'warning', 1: 'success', 2: 'danger' },
replaceValue: {
0: t('order.adminWithdrawOrder.status 0'),
1: t('order.adminWithdrawOrder.status 1'),
2: t('order.adminWithdrawOrder.status 2'),
},
},
{
label: t('order.adminWithdrawOrder.receive_type'),
prop: 'receive_type',
align: 'center',
minWidth: 110,
operator: 'eq',
render: 'tag',
custom: { bank: 'primary', ewallet: 'success', crypto: 'warning' },
replaceValue: {
bank: t('order.adminWithdrawOrder.receive_type_bank'),
ewallet: t('order.adminWithdrawOrder.receive_type_ewallet'),
crypto: t('order.adminWithdrawOrder.receive_type_crypto'),
},
},
{
label: t('order.adminWithdrawOrder.receive_account'),
prop: 'receive_account',
align: 'center',
minWidth: 160,
operator: 'LIKE',
showOverflowTooltip: true,
},
{ label: t('order.adminWithdrawOrder.review_admin_username'), prop: 'reviewAdmin.username', align: 'center', minWidth: 120, operator: 'LIKE' },
{ label: t('order.adminWithdrawOrder.remark'), prop: 'remark', align: 'center', minWidth: 180, operator: 'LIKE', showOverflowTooltip: true },
{
label: t('order.adminWithdrawOrder.create_time'),
prop: 'create_time',
align: 'center',
render: 'datetime',
operator: 'RANGE',
comSearchRender: 'datetime',
sortable: 'custom',
width: 160,
timeFormat: 'yyyy-mm-dd hh:MM:ss',
},
{ label: t('Operate'), align: 'center', width: 90, render: 'buttons', buttons: optButtons, operator: false, fixed: 'right' },
],
},
{}
)
const onStatusFilterChange = () => {
baTable.getData()
}
const loadStats = async () => {
const res = await createAxios({ url: '/admin/order.AdminWithdrawOrder/stats', method: 'get' })
if (res.code !== 1 || !res.data) {
return
}
stats.total_count = Number(res.data.total_count ?? 0)
stats.pending_count = Number(res.data.pending_count ?? 0)
stats.approved_count = Number(res.data.approved_count ?? 0)
stats.rejected_count = Number(res.data.rejected_count ?? 0)
stats.total_amount = String(res.data.total_amount ?? '0.00')
stats.pending_amount = String(res.data.pending_amount ?? '0.00')
stats.approved_amount = String(res.data.approved_amount ?? '0.00')
}
baTable.before.getData = () => {
const filter = baTable.table.filter || {}
const searchRaw = filter.search
const search = Array.isArray(searchRaw)
? searchRaw.filter((item: any) => item && item.field !== 'status' && item.field !== 'receive_type')
: []
if (statusFilterMode.value === 'pending') {
search.push({ field: 'status', operator: 'eq', val: 0 })
} else if (statusFilterMode.value === 'approved') {
search.push({ field: 'status', operator: 'eq', val: 1 })
} else if (statusFilterMode.value === 'rejected') {
search.push({ field: 'status', operator: 'eq', val: 2 })
}
if (receiveTypeFilterMode.value !== 'all') {
search.push({ field: 'receive_type', operator: 'eq', val: receiveTypeFilterMode.value })
}
filter.search = search
baTable.table.filter = filter
}
baTable.after.getData = () => {
void loadStats()
}
provide('baTable', baTable)
onMounted(() => {
baTable.table.ref = tableRef.value
baTable.mount()
baTable.getData()?.then(() => {
baTable.initSort()
baTable.dragSort()
})
void loadStats()
})
</script>
<style scoped lang="scss">
.withdraw-stats-cards {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 10px;
margin: 10px 0;
}
.withdraw-stat-card .label {
font-size: 12px;
color: var(--el-text-color-secondary);
}
.withdraw-stat-card .value {
margin-top: 6px;
font-size: 20px;
font-weight: 600;
color: var(--el-text-color-primary);
}
.withdraw-filter-row {
margin-bottom: 10px;
display: flex;
gap: 10px;
align-items: center;
}
.receive-type-filter {
width: 180px;
}
@media (max-width: 900px) {
.withdraw-stats-cards {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
</style>

View File

@@ -49,7 +49,7 @@ function formatAmount(_row: anyObj, _column: any, cellValue: unknown) {
if (!Number.isFinite(n)) {
return String(cellValue)
}
return n.toFixed(4)
return n.toFixed(2)
}
const baTable = new baTableClass(

View File

@@ -1,214 +0,0 @@
<template>
<div class="default-main ba-table-box">
<el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info" show-icon />
<TableHeader
:buttons="['refresh', 'comSearch', 'quickSearch', 'columnDisplay']"
:quick-search-placeholder="t('Quick search placeholder', { fields: t('order.depositChannelOrder.quick Search Fields') })"
></TableHeader>
<Table ref="tableRef"></Table>
<PopupForm />
</div>
</template>
<script setup lang="ts">
import { onMounted, provide, useTemplateRef } from 'vue'
import { useI18n } from 'vue-i18n'
import PopupForm from '../depositOrder/popupForm.vue'
import { baTableApi } from '/@/api/common'
import { defaultOptButtons } from '/@/components/table'
import TableHeader from '/@/components/table/header/index.vue'
import Table from '/@/components/table/index.vue'
import baTableClass from '/@/utils/baTable'
defineOptions({
name: 'order/depositChannelOrder',
})
const { t } = useI18n()
const tableRef = useTemplateRef('tableRef')
const optButtons: OptButton[] = defaultOptButtons(['edit'])
function formatAmount(_row: anyObj, _column: any, cellValue: unknown) {
if (cellValue === null || cellValue === undefined || cellValue === '') {
return '-'
}
const s = String(cellValue).trim().replace(',', '.')
const n = parseFloat(s)
if (!Number.isFinite(n)) {
return String(cellValue)
}
return n.toFixed(2)
}
const baTable = new baTableClass(
new baTableApi('/admin/order.DepositChannelOrder/'),
{
pk: 'id',
column: [
{ type: 'selection', align: 'center', operator: false },
{ label: t('order.depositOrder.id'), prop: 'id', align: 'center', width: 80, operator: 'RANGE', sortable: 'custom' },
{
label: t('order.depositOrder.order_no'),
prop: 'order_no',
align: 'center',
minWidth: 170,
operator: 'LIKE',
operatorPlaceholder: t('Fuzzy query'),
},
{
label: t('order.depositOrder.user_username'),
prop: 'user.username',
align: 'center',
minWidth: 120,
operator: 'LIKE',
operatorPlaceholder: t('Fuzzy query'),
render: 'tags',
},
{
label: t('order.depositOrder.channel_name'),
prop: 'channel.name',
align: 'center',
minWidth: 110,
operator: 'LIKE',
operatorPlaceholder: t('Fuzzy query'),
render: 'tags',
},
{
label: t('order.depositOrder.amount'),
prop: 'amount',
align: 'center',
minWidth: 110,
operator: 'RANGE',
formatter: formatAmount,
},
{
label: t('order.depositOrder.bonus_amount'),
prop: 'bonus_amount',
align: 'center',
minWidth: 110,
operator: 'RANGE',
formatter: formatAmount,
},
{
label: t('order.depositOrder.status'),
prop: 'status',
align: 'center',
width: 100,
operator: 'eq',
render: 'tag',
effect: 'dark',
custom: {
'0': 'info',
'1': 'success',
'2': 'danger',
'3': 'warning',
},
replaceValue: {
'0': t('order.depositOrder.status 0'),
'1': t('order.depositOrder.status 1'),
'2': t('order.depositOrder.status 2'),
'3': t('order.depositOrder.status 3'),
},
},
{
label: t('order.depositOrder.pay_channel'),
prop: 'pay_channel',
align: 'center',
minWidth: 130,
operator: 'LIKE',
operatorPlaceholder: t('Fuzzy query'),
},
{
label: t('order.depositOrder.deposit_tier_id'),
prop: 'deposit_tier_id',
align: 'center',
minWidth: 120,
operator: 'LIKE',
operatorPlaceholder: t('Fuzzy query'),
show: false,
},
{
label: t('order.depositOrder.pay_time'),
prop: 'pay_time',
align: 'center',
render: 'datetime',
operator: 'RANGE',
comSearchRender: 'datetime',
sortable: 'custom',
width: 170,
timeFormat: 'yyyy-mm-dd hh:MM:ss',
},
{
label: t('order.depositOrder.idempotency_key'),
prop: 'idempotency_key',
align: 'center',
minWidth: 170,
operator: 'LIKE',
operatorPlaceholder: t('Fuzzy query'),
showOverflowTooltip: true,
show: false,
},
{
label: t('order.depositOrder.remark'),
prop: 'remark',
align: 'center',
minWidth: 150,
operator: 'LIKE',
operatorPlaceholder: t('Fuzzy query'),
showOverflowTooltip: true,
},
{
label: t('order.depositOrder.create_time'),
prop: 'create_time',
align: 'center',
render: 'datetime',
operator: 'RANGE',
comSearchRender: 'datetime',
sortable: 'custom',
width: 170,
timeFormat: 'yyyy-mm-dd hh:MM:ss',
},
{
label: t('order.depositOrder.update_time'),
prop: 'update_time',
align: 'center',
render: 'datetime',
operator: 'RANGE',
comSearchRender: 'datetime',
sortable: 'custom',
width: 170,
timeFormat: 'yyyy-mm-dd hh:MM:ss',
show: false,
},
{
label: t('Operate'),
align: 'center',
width: 90,
render: 'buttons',
buttons: optButtons,
operator: false,
fixed: 'right',
},
],
},
{
defaultItems: { status: 0, amount: '0.0000', bonus_amount: '0.0000' },
}
)
provide('baTable', baTable)
onMounted(() => {
baTable.table.ref = tableRef.value
baTable.mount()
baTable.getData()?.then(() => {
baTable.initSort()
baTable.dragSort()
})
})
</script>
<style scoped lang="scss"></style>

View File

@@ -195,7 +195,7 @@ const baTable = new baTableClass(
],
},
{
defaultItems: { status: 0, amount: '0.0000', bonus_amount: '0.0000' },
defaultItems: { status: 0, amount: '0.00', bonus_amount: '0.00' },
}
)

View File

@@ -31,6 +31,17 @@ const { t } = useI18n()
const tableRef = useTemplateRef('tableRef')
const optButtons: OptButton[] = defaultOptButtons(['edit'])
function formatAmount(_row: anyObj, _column: any, cellValue: unknown) {
if (cellValue === null || cellValue === undefined || cellValue === '') {
return '-'
}
const n = Number(cellValue)
if (!Number.isFinite(n)) {
return String(cellValue)
}
return n.toFixed(2)
}
const baTable = new baTableClass(
new baTableApi('/admin/order.WithdrawOrder/'),
{
@@ -65,9 +76,36 @@ const baTable = new baTableClass(
operatorPlaceholder: t('Fuzzy query'),
render: 'tags',
},
{ label: t('order.withdrawOrder.amount'), prop: 'amount', align: 'center', minWidth: 110, operator: 'RANGE' },
{ label: t('order.withdrawOrder.fee'), prop: 'fee', align: 'center', minWidth: 110, operator: 'RANGE' },
{ label: t('order.withdrawOrder.actual_amount'), prop: 'actual_amount', align: 'center', minWidth: 110, operator: 'RANGE' },
{ label: t('order.withdrawOrder.amount'), prop: 'amount', align: 'center', minWidth: 110, operator: 'RANGE', formatter: formatAmount },
{ label: t('order.withdrawOrder.fee'), prop: 'fee', align: 'center', minWidth: 110, operator: 'RANGE', formatter: formatAmount },
{ label: t('order.withdrawOrder.actual_amount'), prop: 'actual_amount', align: 'center', minWidth: 110, operator: 'RANGE', formatter: formatAmount },
{
label: t('order.withdrawOrder.receive_type'),
prop: 'receive_type',
align: 'center',
minWidth: 120,
operator: 'LIKE',
operatorPlaceholder: t('Fuzzy query'),
},
{
label: t('order.withdrawOrder.receive_account'),
prop: 'receive_account',
align: 'center',
minWidth: 180,
operator: 'LIKE',
operatorPlaceholder: t('Fuzzy query'),
showOverflowTooltip: true,
},
{
label: t('order.withdrawOrder.idempotency_key'),
prop: 'idempotency_key',
align: 'center',
minWidth: 170,
operator: 'LIKE',
operatorPlaceholder: t('Fuzzy query'),
showOverflowTooltip: true,
show: false,
},
{
label: t('order.withdrawOrder.status'),
prop: 'status',
@@ -144,7 +182,7 @@ const baTable = new baTableClass(
],
},
{
defaultItems: { status: 0, amount: '0.0000', fee: '0.0000', actual_amount: '0.0000' },
defaultItems: { status: 0, amount: '0.00', fee: '0.00', actual_amount: '0.00' },
}
)

View File

@@ -39,6 +39,15 @@
<el-form-item :label="t('order.withdrawOrder.create_time')">
<el-input :model-value="form.create_time_text" readonly />
</el-form-item>
<el-form-item :label="t('order.withdrawOrder.receive_type')">
<el-input :model-value="form.receive_type || '-'" readonly />
</el-form-item>
<el-form-item :label="t('order.withdrawOrder.receive_account')">
<el-input :model-value="form.receive_account || '-'" readonly />
</el-form-item>
<el-form-item :label="t('order.withdrawOrder.idempotency_key')">
<el-input :model-value="form.idempotency_key || '-'" readonly />
</el-form-item>
<el-form-item :label="t('order.withdrawOrder.amount')" prop="amount">
<el-input-number
@@ -161,6 +170,9 @@ const form = reactive({
create_time_text: '',
review_admin_text: '-',
review_time_text: '-',
idempotency_key: '',
receive_type: '',
receive_account: '',
amount: 0,
fee: 0,
status: 0,
@@ -207,6 +219,9 @@ const hydrate = () => {
form.fee = parseNumber(row['fee'])
form.status = Number(row['status'] ?? 0)
form.remark = String(row['remark'] ?? '')
form.idempotency_key = String(row['idempotency_key'] ?? '')
form.receive_type = String(row['receive_type'] ?? '')
form.receive_account = String(row['receive_account'] ?? '')
form.create_time_text = formatTime(row['create_time'])
form.review_time_text = formatTime(row['review_time'])
form.user_text = resolveRelationText(row, 'user', row['user_id'])
@@ -316,8 +331,8 @@ const submitApprove = async () => {
method: 'POST',
data: {
id: form.id,
amount: form.amount.toFixed(4),
fee: form.fee.toFixed(4),
amount: form.amount.toFixed(2),
fee: form.fee.toFixed(2),
},
},
{ showSuccessMessage: true }

View File

@@ -27,6 +27,20 @@
</div>
</div>
<div class="admin-info-form">
<el-card shadow="never" class="wallet-card">
<template #header>
<div class="wallet-card-header">
<span>{{ t('routine.adminInfo.admin_wallet') }}</span>
<el-button type="primary" link @click="state.withdrawDialogVisible = true">{{ t('routine.adminInfo.withdraw') }}</el-button>
</div>
</template>
<div class="wallet-metrics">
<div>{{ t('routine.adminInfo.wallet_balance') }}{{ state.wallet.balance }}</div>
<div>{{ t('routine.adminInfo.wallet_frozen_balance') }}{{ state.wallet.frozen_balance }}</div>
<div>{{ t('routine.adminInfo.wallet_total_income') }}{{ state.wallet.total_income }}</div>
<div>{{ t('routine.adminInfo.wallet_total_withdraw') }}{{ state.wallet.total_withdraw }}</div>
</div>
</el-card>
<el-form
@keyup.enter="onSubmit()"
:key="state.formKey"
@@ -99,13 +113,40 @@
</el-card>
</el-col>
</el-row>
<el-dialog v-model="state.withdrawDialogVisible" :title="t('routine.adminInfo.withdraw_apply_title')" width="520px" :close-on-click-modal="false">
<el-form label-width="100px">
<el-form-item :label="t('routine.adminInfo.withdraw_coin')">
<el-input v-model="state.withdrawForm.withdraw_coin" :placeholder="t('routine.adminInfo.withdraw_coin_placeholder')" />
</el-form-item>
<el-form-item :label="t('routine.adminInfo.receive_type')">
<el-select v-model="state.withdrawForm.receive_type" class="w100" :placeholder="t('routine.adminInfo.receive_type_placeholder')">
<el-option label="bank" value="bank" />
<el-option label="ewallet" value="ewallet" />
<el-option label="crypto" value="crypto" />
</el-select>
</el-form-item>
<el-form-item :label="t('routine.adminInfo.receive_account')">
<el-input v-model="state.withdrawForm.receive_account" :placeholder="t('routine.adminInfo.receive_account_placeholder')" />
</el-form-item>
<el-form-item :label="t('routine.adminInfo.idempotency_key')">
<el-input v-model="state.withdrawForm.idempotency_key" :placeholder="t('routine.adminInfo.idempotency_key_placeholder')" />
</el-form-item>
<el-form-item :label="t('routine.adminInfo.remark')">
<el-input v-model="state.withdrawForm.remark" type="textarea" :rows="2" />
</el-form-item>
</el-form>
<template #footer>
<el-button @click="state.withdrawDialogVisible = false">{{ t('Cancel') }}</el-button>
<el-button type="primary" :loading="state.withdrawSubmitting" @click="onWithdrawApply">{{ t('routine.adminInfo.submit_apply') }}</el-button>
</template>
</el-dialog>
</div>
</template>
<script setup lang="ts">
import { reactive, useTemplateRef } from 'vue'
import { useI18n } from 'vue-i18n'
import { index, log, postData } from '/@/api/backend/routine/AdminInfo'
import { index, log, postData, walletSummary, withdrawApply } from '/@/api/backend/routine/AdminInfo'
import type { FormItemRule } from 'element-plus'
import { fullUrl, onResetForm, timeFormat } from '/@/utils/common'
import { uuid } from '../../../utils/random'
@@ -137,6 +178,10 @@ const state: {
logPageSize: number
logTotal: number
logLoading: boolean
wallet: { balance: string; frozen_balance: string; total_income: string; total_withdraw: string }
withdrawDialogVisible: boolean
withdrawSubmitting: boolean
withdrawForm: { withdraw_coin: string; receive_type: string; receive_account: string; idempotency_key: string; remark: string }
} = reactive({
adminInfo: {},
formKey: uuid(),
@@ -149,6 +194,10 @@ const state: {
logPageSize: 12,
logTotal: 100,
logLoading: true,
wallet: { balance: '0.00', frozen_balance: '0.00', total_income: '0.00', total_withdraw: '0.00' },
withdrawDialogVisible: false,
withdrawSubmitting: false,
withdrawForm: { withdraw_coin: '100.00', receive_type: 'bank', receive_account: '', idempotency_key: '', remark: '' },
})
index().then((res) => {
@@ -165,8 +214,15 @@ index().then((res) => {
},
]
getLog()
loadWalletSummary()
})
const loadWalletSummary = () => {
walletSummary().then((res) => {
state.wallet = res.data?.wallet || state.wallet
})
}
const getLog = () => {
log(state.logFilter)
.then((res) => {
@@ -233,6 +289,26 @@ const onSubmit = () => {
}
})
}
const onWithdrawApply = () => {
state.withdrawSubmitting = true
if (!state.withdrawForm.idempotency_key) {
state.withdrawForm.idempotency_key = `admin_withdraw_${Date.now()}_${Math.floor(Math.random() * 100000)}`
}
withdrawApply({ ...state.withdrawForm })
.then(() => {
state.withdrawDialogVisible = false
state.withdrawForm.withdraw_coin = '100.00'
state.withdrawForm.receive_type = 'bank'
state.withdrawForm.receive_account = ''
state.withdrawForm.idempotency_key = ''
state.withdrawForm.remark = ''
loadWalletSummary()
})
.finally(() => {
state.withdrawSubmitting = false
})
}
</script>
<style scoped lang="scss">
@@ -286,6 +362,24 @@ const onSubmit = () => {
padding: 30px;
}
}
.wallet-card {
margin-bottom: 16px;
}
.wallet-card-header {
display: flex;
justify-content: space-between;
align-items: center;
}
.wallet-metrics {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 8px 12px;
font-size: 13px;
}
.el-card :deep(.el-timeline-item__icon) {
font-size: 10px;
}

View File

@@ -210,6 +210,7 @@ type TreeNode = {
const adminScopeTree = ref<TreeNode[]>([])
const adminIdToChannelId = ref<Record<string, number>>({})
const adminIdToInviteCode = ref<Record<string, string>>({})
const currentAdminId = ref('')
const treeProps = {
value: 'value',
@@ -309,6 +310,8 @@ const loadAdminScopeTree = async () => {
method: 'get',
})
const list = (res.data?.list ?? []) as TreeNode[]
const currentIdRaw = res.data?.current_admin_id
currentAdminId.value = currentIdRaw === undefined || currentIdRaw === null ? '' : String(currentIdRaw)
adminScopeTree.value = list
const { mapCh, mapInv } = buildAdminMapsFromTree(list)
@@ -316,6 +319,14 @@ const loadAdminScopeTree = async () => {
adminIdToInviteCode.value = mapInv
await nextTick()
if (
baTable.form.operate === 'Add' &&
baTable.form.items &&
(baTable.form.items.admin_id === undefined || baTable.form.items.admin_id === null || baTable.form.items.admin_id === '') &&
currentAdminId.value !== ''
) {
baTable.form.items.admin_id = currentAdminId.value
}
const aid = baTable.form.items?.admin_id
if (aid !== undefined && aid !== null && aid !== '') {
onAdminTreeChange(aid as string | number)
@@ -398,6 +409,14 @@ watch(
(op) => {
if (op === 'Add') {
syncRiskFromFlags(0)
if (
baTable.form.items &&
(baTable.form.items.admin_id === undefined || baTable.form.items.admin_id === null || baTable.form.items.admin_id === '') &&
currentAdminId.value !== ''
) {
baTable.form.items.admin_id = currentAdminId.value
onAdminTreeChange(currentAdminId.value)
}
}
}
)