完善接口和后台页面
This commit is contained in:
218
app/common/library/finance/DepositSettlement.php
Normal file
218
app/common/library/finance/DepositSettlement.php
Normal file
@@ -0,0 +1,218 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\library\finance;
|
||||
|
||||
use RuntimeException;
|
||||
use support\think\Db;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* 充值订单结算公共库
|
||||
*
|
||||
* 所有"把 deposit_order 变为成功并给玩家钱包加币"的逻辑必须收敛到这里,
|
||||
* 以便 mock 支付瞬时成功、未来第三方网关回调、历史数据的人工补单共用同一事务边界。
|
||||
*
|
||||
* 关键约束:
|
||||
* - 只结算 status=0 的订单,幂等;重复调用同一订单返回现有结算结果;
|
||||
* - 钱包流水 user_wallet_record 以 "deposit_settle_{order_no}" 为 idempotency_key,保证不重复入账;
|
||||
* - 同时更新 user.coin 与 update_time,user_wallet_record 记录 balance_before/after 快照。
|
||||
*/
|
||||
final class DepositSettlement
|
||||
{
|
||||
public const SOURCE_MOCK_GATEWAY = 'mock_gateway';
|
||||
|
||||
public const SOURCE_ADMIN_APPROVE = 'admin_approve';
|
||||
|
||||
public const SOURCE_THIRD_PARTY = 'third_party';
|
||||
|
||||
/**
|
||||
* 结算指定订单。
|
||||
*
|
||||
* @param int $orderId deposit_order.id
|
||||
* @param string $source 来源(SOURCE_* 常量),写入 remark
|
||||
* @param string $sourceLabel 人类可读描述,写入 remark,如 "mock gateway auto settled"
|
||||
* @param int|null $operatorAdminId 操作管理员 ID(仅管理员审核时有值)
|
||||
* @param string|null $extraRemark 追加到订单 remark(可选)
|
||||
*
|
||||
* @return array{
|
||||
* order_id: int,
|
||||
* order_no: string,
|
||||
* amount: string,
|
||||
* balance_before: string,
|
||||
* balance_after: string,
|
||||
* pay_time: int,
|
||||
* already_settled: bool,
|
||||
* }
|
||||
*
|
||||
* @throws RuntimeException 订单不存在、金额非法、并发冲突等
|
||||
*/
|
||||
public static function settle(
|
||||
int $orderId,
|
||||
string $source,
|
||||
string $sourceLabel,
|
||||
?int $operatorAdminId = null,
|
||||
?string $extraRemark = null
|
||||
): array {
|
||||
if ($orderId <= 0) {
|
||||
throw new RuntimeException('订单 ID 非法');
|
||||
}
|
||||
|
||||
$order = Db::name('deposit_order')->where('id', $orderId)->find();
|
||||
if (!$order) {
|
||||
throw new RuntimeException('订单不存在');
|
||||
}
|
||||
|
||||
$orderNo = is_string($order['order_no']) ? $order['order_no'] : strval($order['order_no']);
|
||||
if ($orderNo === '') {
|
||||
throw new RuntimeException('订单号为空');
|
||||
}
|
||||
|
||||
$statusRaw = $order['status'] ?? 0;
|
||||
$status = is_numeric($statusRaw) ? intval($statusRaw) : 0;
|
||||
|
||||
// 如果已结算,直接返回已有结果(幂等)
|
||||
if ($status === 1) {
|
||||
$userId = is_numeric($order['user_id'] ?? null) ? intval($order['user_id']) : 0;
|
||||
$coinAfter = '0.0000';
|
||||
if ($userId > 0) {
|
||||
$coin = Db::name('user')->where('id', $userId)->value('coin');
|
||||
$coinAfter = is_string($coin) ? $coin : strval($coin);
|
||||
}
|
||||
$amt = self::amountString($order['amount'] ?? '0');
|
||||
$bns = self::amountString($order['bonus_amount'] ?? '0');
|
||||
return [
|
||||
'order_id' => $orderId,
|
||||
'order_no' => $orderNo,
|
||||
'amount' => $amt,
|
||||
'bonus_amount' => $bns,
|
||||
'credit' => bcadd($amt, $bns, 4),
|
||||
'balance_before' => $coinAfter,
|
||||
'balance_after' => $coinAfter,
|
||||
'pay_time' => is_numeric($order['pay_time'] ?? null) ? intval($order['pay_time']) : 0,
|
||||
'already_settled' => true,
|
||||
];
|
||||
}
|
||||
|
||||
if ($status !== 0) {
|
||||
throw new RuntimeException('订单状态不允许结算');
|
||||
}
|
||||
|
||||
$amount = self::amountString($order['amount'] ?? '0');
|
||||
if (bccomp($amount, '0', 4) <= 0) {
|
||||
throw new RuntimeException('订单金额异常');
|
||||
}
|
||||
$bonus = self::amountString($order['bonus_amount'] ?? '0');
|
||||
if (bccomp($bonus, '0', 4) < 0) {
|
||||
$bonus = '0.0000';
|
||||
}
|
||||
$credit = bcadd($amount, $bonus, 4);
|
||||
|
||||
$userId = is_numeric($order['user_id'] ?? null) ? intval($order['user_id']) : 0;
|
||||
if ($userId <= 0) {
|
||||
throw new RuntimeException('订单所属玩家无效');
|
||||
}
|
||||
|
||||
$user = Db::name('user')->where('id', $userId)->find();
|
||||
if (!$user) {
|
||||
throw new RuntimeException('玩家不存在');
|
||||
}
|
||||
|
||||
$channelId = is_numeric($order['channel_id'] ?? null) ? intval($order['channel_id']) : null;
|
||||
$balanceBefore = self::amountString($user['coin'] ?? '0');
|
||||
$balanceAfter = bcadd($balanceBefore, $credit, 4);
|
||||
|
||||
$now = time();
|
||||
$baseRemark = is_string($order['remark'] ?? null) ? $order['remark'] : '';
|
||||
// 备注包含充值与赠送的明细,方便后续稽核
|
||||
$detail = sprintf('amount=%s,bonus=%s,credit=%s', $amount, $bonus, $credit);
|
||||
$note = sprintf('[%s] %s (%s)', $source, $sourceLabel, $detail);
|
||||
$combined = $baseRemark === '' ? $note : ($baseRemark . ' | ' . $note);
|
||||
if ($extraRemark !== null && $extraRemark !== '') {
|
||||
$combined .= ' | ' . $extraRemark;
|
||||
}
|
||||
$finalRemark = mb_substr($combined, 0, 255);
|
||||
|
||||
$walletIdem = 'deposit_settle_' . $orderNo;
|
||||
|
||||
Db::startTrans();
|
||||
try {
|
||||
$affected = Db::name('deposit_order')
|
||||
->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,
|
||||
]);
|
||||
if ($affected <= 0) {
|
||||
throw new RuntimeException('订单状态已变更,请刷新后重试');
|
||||
}
|
||||
|
||||
Db::name('user')->where('id', $userId)->update([
|
||||
'coin' => $balanceAfter,
|
||||
'update_time' => $now,
|
||||
]);
|
||||
|
||||
$walletExists = Db::name('user_wallet_record')
|
||||
->where('idempotency_key', $walletIdem)
|
||||
->value('id');
|
||||
if (!$walletExists) {
|
||||
Db::name('user_wallet_record')->insert([
|
||||
'user_id' => $userId,
|
||||
'channel_id' => $channelId,
|
||||
'biz_type' => 'deposit',
|
||||
'direction' => 1,
|
||||
'amount' => $credit,
|
||||
'balance_before' => $balanceBefore,
|
||||
'balance_after' => $balanceAfter,
|
||||
'ref_type' => 'deposit_order',
|
||||
'ref_id' => $orderId,
|
||||
'idempotency_key' => $walletIdem,
|
||||
'operator_admin_id' => $operatorAdminId,
|
||||
'remark' => mb_substr($note, 0, 500),
|
||||
'create_time' => $now,
|
||||
]);
|
||||
}
|
||||
|
||||
Db::commit();
|
||||
} catch (Throwable $e) {
|
||||
Db::rollback();
|
||||
throw new RuntimeException($e->getMessage());
|
||||
}
|
||||
|
||||
return [
|
||||
'order_id' => $orderId,
|
||||
'order_no' => $orderNo,
|
||||
'amount' => $amount,
|
||||
'bonus_amount' => $bonus,
|
||||
'credit' => $credit,
|
||||
'balance_before' => $balanceBefore,
|
||||
'balance_after' => $balanceAfter,
|
||||
'pay_time' => $now,
|
||||
'already_settled' => false,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 将任意数值输入格式化为 4 位小数字符串(不做强制类型转换)
|
||||
*/
|
||||
private static function amountString($raw): string
|
||||
{
|
||||
if (is_string($raw)) {
|
||||
$s = trim($raw);
|
||||
} elseif (is_int($raw) || is_float($raw)) {
|
||||
$s = strval($raw);
|
||||
} else {
|
||||
return '0.0000';
|
||||
}
|
||||
if (!is_numeric($s)) {
|
||||
return '0.0000';
|
||||
}
|
||||
return bcadd($s, '0', 4);
|
||||
}
|
||||
}
|
||||
164
app/common/library/finance/WithdrawFlow.php
Normal file
164
app/common/library/finance/WithdrawFlow.php
Normal file
@@ -0,0 +1,164 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\library\finance;
|
||||
|
||||
use support\think\Db;
|
||||
|
||||
/**
|
||||
* 提现打码量(流水)门槛工具库
|
||||
*
|
||||
* 业务口径(打码量即提现配额模型):
|
||||
* - 每笔提现消耗等额打码配额:折算 = withdraw_coin × ratio
|
||||
* - lifetime_withdrawable_from_flow = bet_flow_coin / ratio
|
||||
* - max_withdraw_by_flow = max(0, lifetime_withdrawable_from_flow - total_withdraw_coin)
|
||||
* - 单笔上限:max_withdrawable = min(coin_balance, max_withdraw_by_flow)
|
||||
* - ratio 来自 game_config.withdraw_bet_flow_ratio;ratio = 0 代表不限制打码量,此时
|
||||
* max_withdraw_by_flow 视为"无限大"(由 UNLIMITED_FLOW 哨兵值表示,API 层兜底用余额)
|
||||
*
|
||||
* 向后兼容:原门槛 bet_flow_coin >= (total_deposit - total_withdraw) × ratio 已被
|
||||
* "单笔上限 ≤ max_withdraw_by_flow" 取代且语义等价更细腻:任何通过新校验的请求必然
|
||||
* 也满足旧门槛口径。字段 required_bet_flow / remaining_bet_flow / eligible 保留仅作展示。
|
||||
*/
|
||||
final class WithdrawFlow
|
||||
{
|
||||
public const CONFIG_KEY = 'withdraw_bet_flow_ratio';
|
||||
|
||||
public const DEFAULT_RATIO = '1.0000';
|
||||
|
||||
/** 当 ratio = 0(不限打码)时,max_withdraw_by_flow 用此哨兵表示"无限"。14 位整数位足够覆盖任何业务金额。 */
|
||||
public const UNLIMITED_FLOW = '99999999999999.9999';
|
||||
|
||||
/** 单用户最多允许同时存在的「待审核」(withdraw_order.status=0) 提现订单数。 */
|
||||
public const MAX_PENDING_WITHDRAW = 3;
|
||||
|
||||
/**
|
||||
* 读取当前打码倍数(字符串 4 位小数,至少 0)
|
||||
*/
|
||||
public static function ratio(): string
|
||||
{
|
||||
$row = Db::name('game_config')->where('config_key', self::CONFIG_KEY)->find();
|
||||
if (!$row) {
|
||||
return self::DEFAULT_RATIO;
|
||||
}
|
||||
$val = $row['config_value'] ?? '';
|
||||
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';
|
||||
}
|
||||
return $normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化金额字段到 4 位小数字符串,非法输入返回 '0.0000'
|
||||
*/
|
||||
public static function amountString($raw): string
|
||||
{
|
||||
if ($raw === null || $raw === '') {
|
||||
return '0.0000';
|
||||
}
|
||||
if (is_string($raw)) {
|
||||
$s = trim($raw);
|
||||
} elseif (is_int($raw) || is_float($raw)) {
|
||||
$s = strval($raw);
|
||||
} else {
|
||||
return '0.0000';
|
||||
}
|
||||
if (!is_numeric($s)) {
|
||||
return '0.0000';
|
||||
}
|
||||
return bcadd($s, '0', 4);
|
||||
}
|
||||
|
||||
/**
|
||||
* 核算玩家当前打码量状态
|
||||
*
|
||||
* @param array{
|
||||
* total_deposit_coin?: mixed,
|
||||
* total_withdraw_coin?: mixed,
|
||||
* bet_flow_coin?: mixed,
|
||||
* }|null $userSnapshot 允许外部传入字典(节省一次查询);为 null 时按 $userId 从库取
|
||||
*
|
||||
* @return array{
|
||||
* ratio: string,
|
||||
* net_deposit: string,
|
||||
* required_bet_flow: string,
|
||||
* bet_flow_coin: string,
|
||||
* remaining_bet_flow: string,
|
||||
* eligible: bool,
|
||||
* max_withdraw_by_flow: string,
|
||||
* flow_unlimited: bool,
|
||||
* }
|
||||
*/
|
||||
public static function status(?int $userId, ?array $userSnapshot = null): array
|
||||
{
|
||||
if ($userSnapshot === null && $userId !== null) {
|
||||
$userSnapshot = Db::name('user')
|
||||
->field(['total_deposit_coin', 'total_withdraw_coin', 'bet_flow_coin'])
|
||||
->where('id', $userId)
|
||||
->find();
|
||||
}
|
||||
$userSnapshot = is_array($userSnapshot) ? $userSnapshot : [];
|
||||
|
||||
$deposit = self::amountString($userSnapshot['total_deposit_coin'] ?? '0');
|
||||
$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';
|
||||
}
|
||||
|
||||
$ratio = self::ratio();
|
||||
$required = bcmul($net, $ratio, 4);
|
||||
$remaining = bcsub($required, $flow, 4);
|
||||
if (bccomp($remaining, '0', 4) < 0) {
|
||||
$remaining = '0.0000';
|
||||
}
|
||||
$eligible = bccomp($flow, $required, 4) >= 0;
|
||||
|
||||
// max_withdraw_by_flow = max(0, bet_flow_coin / ratio - total_withdraw_coin)
|
||||
$unlimited = bccomp($ratio, '0', 4) === 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';
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'ratio' => $ratio,
|
||||
'net_deposit' => $net,
|
||||
'required_bet_flow' => $required,
|
||||
'bet_flow_coin' => $flow,
|
||||
'remaining_bet_flow' => $remaining,
|
||||
'eligible' => $eligible,
|
||||
'max_withdraw_by_flow' => $maxByFlow,
|
||||
'flow_unlimited' => $unlimited,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 取单笔最大可提现额 = min(coin_balance, max_withdraw_by_flow)。
|
||||
* 返回值为 4 位小数字符串,已与 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 (!empty($flowStatus['flow_unlimited'])) {
|
||||
return $coin;
|
||||
}
|
||||
$byFlow = self::amountString($flowStatus['max_withdraw_by_flow'] ?? '0');
|
||||
return bccomp($coin, $byFlow, 4) <= 0 ? $coin : $byFlow;
|
||||
}
|
||||
}
|
||||
351
app/common/library/game/DepositTier.php
Normal file
351
app/common/library/game/DepositTier.php
Normal file
@@ -0,0 +1,351 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\library\game;
|
||||
|
||||
use InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* 充值档位(game_config.deposit_tier):仅存 JSON 数组
|
||||
*
|
||||
* 每一项字段(mock/第三方支付模式,已不再保存收款账户信息;支持中英文双语):
|
||||
* - id : string,档位稳定 ID(如 t_xxxxxxxx)
|
||||
* - title : string,档位中文名称(必填,前端中文环境展示)
|
||||
* - title_en : string,档位英文名称(可选,前端英文环境展示;为空时回退到 title)
|
||||
* - amount : string,充值金额(4 位小数)
|
||||
* - bonus_amount : string,赠送金额(4 位小数,可为 0)
|
||||
* - desc : string,档位中文描述(可空,<=255)
|
||||
* - desc_en : string,档位英文描述(可空,<=255,为空时回退到 desc)
|
||||
* - sort : int,排序权重(小值在前)
|
||||
* - status : int,0=停用,1=启用
|
||||
*
|
||||
* 历史数据兼容:老字段 name 会在 title 缺失时作为 title 兜底(更老的 account_name 亦会兜底)。
|
||||
*/
|
||||
final class DepositTier
|
||||
{
|
||||
public const CONFIG_KEY = 'deposit_tier';
|
||||
|
||||
/**
|
||||
* 从 game_config.config_value 中解析出档位数组(容错)
|
||||
*
|
||||
* @return list<array{
|
||||
* id: string,
|
||||
* title: string,
|
||||
* title_en: string,
|
||||
* amount: string,
|
||||
* bonus_amount: string,
|
||||
* desc: string,
|
||||
* desc_en: string,
|
||||
* sort: int,
|
||||
* status: int,
|
||||
* }>
|
||||
*/
|
||||
public static function parseFromConfigValue($raw): array
|
||||
{
|
||||
if (!is_string($raw) || trim($raw) === '') {
|
||||
return [];
|
||||
}
|
||||
$decoded = json_decode($raw, true);
|
||||
if (!is_array($decoded)) {
|
||||
return [];
|
||||
}
|
||||
if (isset($decoded['tiers']) && is_array($decoded['tiers'])) {
|
||||
$list = $decoded['tiers'];
|
||||
} else {
|
||||
$list = $decoded;
|
||||
}
|
||||
return self::normalizeList($list);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<mixed> $items
|
||||
*/
|
||||
public static function normalizeList(array $items): array
|
||||
{
|
||||
$out = [];
|
||||
foreach ($items as $row) {
|
||||
if (!is_array($row)) {
|
||||
continue;
|
||||
}
|
||||
$id = isset($row['id']) && is_string($row['id']) ? trim($row['id']) : '';
|
||||
if ($id === '') {
|
||||
$id = self::generateId();
|
||||
}
|
||||
|
||||
$title = self::stringField($row, 'title');
|
||||
if ($title === '') {
|
||||
// 兼容历史:字段名 name 或更老的 account_name
|
||||
$title = self::stringField($row, 'name');
|
||||
if ($title === '') {
|
||||
$title = self::stringField($row, 'account_name');
|
||||
}
|
||||
}
|
||||
$titleEn = self::stringField($row, 'title_en');
|
||||
|
||||
$amount = self::normalizeAmount($row['amount'] ?? '');
|
||||
$bonus = self::normalizeAmount($row['bonus_amount'] ?? '0');
|
||||
|
||||
$desc = self::stringField($row, 'desc');
|
||||
if ($desc === '') {
|
||||
$desc = self::stringField($row, 'remark');
|
||||
}
|
||||
$descEn = self::stringField($row, 'desc_en');
|
||||
|
||||
$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;
|
||||
|
||||
$out[] = [
|
||||
'id' => $id,
|
||||
'title' => $title,
|
||||
'title_en' => $titleEn,
|
||||
'amount' => $amount,
|
||||
'bonus_amount' => $bonus,
|
||||
'desc' => $desc,
|
||||
'desc_en' => $descEn,
|
||||
'sort' => $sort,
|
||||
'status' => $status,
|
||||
];
|
||||
}
|
||||
usort($out, static function (array $a, array $b): int {
|
||||
if ($a['sort'] !== $b['sort']) {
|
||||
return $a['sort'] <=> $b['sort'];
|
||||
}
|
||||
$ida = is_string($a['id']) ? $a['id'] : '';
|
||||
$idb = is_string($b['id']) ? $b['id'] : '';
|
||||
return strcmp($ida, $idb);
|
||||
});
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验 POST 数据并输出用于入库的清洁数据
|
||||
*
|
||||
* @param list<array<string, mixed>> $items
|
||||
*
|
||||
* @throws InvalidArgumentException
|
||||
*/
|
||||
public static function prepareItemsForSave(array $items): array
|
||||
{
|
||||
$seenId = [];
|
||||
$out = [];
|
||||
foreach ($items as $idx => $row) {
|
||||
$no = $idx + 1;
|
||||
if (!is_array($row)) {
|
||||
throw new InvalidArgumentException('第 ' . $no . ' 行格式错误');
|
||||
}
|
||||
|
||||
$id = isset($row['id']) && is_string($row['id']) ? trim($row['id']) : '';
|
||||
if ($id === '') {
|
||||
$id = self::generateId();
|
||||
}
|
||||
if (!preg_match('/^[a-zA-Z0-9_\-]{1,32}$/', $id)) {
|
||||
throw new InvalidArgumentException('第 ' . $no . ' 行 ID 非法');
|
||||
}
|
||||
if (isset($seenId[$id])) {
|
||||
throw new InvalidArgumentException('档位 ID 重复:' . $id);
|
||||
}
|
||||
$seenId[$id] = true;
|
||||
|
||||
$title = self::stringField($row, 'title');
|
||||
if ($title === '') {
|
||||
// 兼容上游(例如自动迁移脚本)传递历史 name 字段
|
||||
$title = self::stringField($row, 'name');
|
||||
}
|
||||
if ($title === '') {
|
||||
throw new InvalidArgumentException('第 ' . $no . ' 行中文充值名称不能为空');
|
||||
}
|
||||
if (mb_strlen($title) > 64) {
|
||||
throw new InvalidArgumentException('第 ' . $no . ' 行中文充值名称过长');
|
||||
}
|
||||
|
||||
$titleEn = self::stringField($row, 'title_en');
|
||||
if (mb_strlen($titleEn) > 64) {
|
||||
throw new InvalidArgumentException('第 ' . $no . ' 行英文充值名称过长');
|
||||
}
|
||||
|
||||
$amount = self::normalizeAmount($row['amount'] ?? '');
|
||||
if (bccomp($amount, '0', 4) <= 0) {
|
||||
throw new InvalidArgumentException('第 ' . $no . ' 行充值金额必须大于 0');
|
||||
}
|
||||
|
||||
$bonus = self::normalizeAmount($row['bonus_amount'] ?? '0');
|
||||
if (bccomp($bonus, '0', 4) < 0) {
|
||||
throw new InvalidArgumentException('第 ' . $no . ' 行赠送金额不能为负数');
|
||||
}
|
||||
|
||||
$desc = self::stringField($row, 'desc');
|
||||
if (mb_strlen($desc) > 255) {
|
||||
throw new InvalidArgumentException('第 ' . $no . ' 行中文描述过长');
|
||||
}
|
||||
|
||||
$descEn = self::stringField($row, 'desc_en');
|
||||
if (mb_strlen($descEn) > 255) {
|
||||
throw new InvalidArgumentException('第 ' . $no . ' 行英文描述过长');
|
||||
}
|
||||
|
||||
$sort = isset($row['sort']) && is_numeric($row['sort']) ? intval($row['sort']) : 0;
|
||||
$statusRaw = isset($row['status']) && is_numeric($row['status']) ? intval($row['status']) : 1;
|
||||
$status = $statusRaw === 1 ? 1 : 0;
|
||||
|
||||
$out[] = [
|
||||
'id' => $id,
|
||||
'title' => $title,
|
||||
'title_en' => $titleEn,
|
||||
'amount' => $amount,
|
||||
'bonus_amount' => $bonus,
|
||||
'desc' => $desc,
|
||||
'desc_en' => $descEn,
|
||||
'sort' => $sort,
|
||||
'status' => $status,
|
||||
];
|
||||
}
|
||||
|
||||
usort($out, static function (array $a, array $b): int {
|
||||
if ($a['sort'] !== $b['sort']) {
|
||||
return $a['sort'] <=> $b['sort'];
|
||||
}
|
||||
$ida = is_string($a['id']) ? $a['id'] : '';
|
||||
$idb = is_string($b['id']) ? $b['id'] : '';
|
||||
return strcmp($ida, $idb);
|
||||
});
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array<string, mixed>> $items
|
||||
*/
|
||||
public static function encodeForDb(array $items): string
|
||||
{
|
||||
$encoded = json_encode($items, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
if ($encoded === false) {
|
||||
throw new InvalidArgumentException('JSON 编码失败');
|
||||
}
|
||||
return $encoded;
|
||||
}
|
||||
|
||||
/**
|
||||
* 过滤出启用档位并按 sort 升序,供移动端选择
|
||||
*/
|
||||
public static function publicList(array $items): array
|
||||
{
|
||||
$enabled = array_values(array_filter($items, static function (array $row): bool {
|
||||
if (!isset($row['status'])) {
|
||||
return false;
|
||||
}
|
||||
$val = is_numeric($row['status']) ? intval($row['status']) : 0;
|
||||
return $val === 1;
|
||||
}));
|
||||
usort($enabled, static function (array $a, array $b): int {
|
||||
$sa = isset($a['sort']) && is_numeric($a['sort']) ? intval($a['sort']) : 0;
|
||||
$sb = isset($b['sort']) && is_numeric($b['sort']) ? intval($b['sort']) : 0;
|
||||
if ($sa !== $sb) {
|
||||
return $sa <=> $sb;
|
||||
}
|
||||
$ida = isset($a['id']) && is_string($a['id']) ? $a['id'] : '';
|
||||
$idb = isset($b['id']) && is_string($b['id']) ? $b['id'] : '';
|
||||
return strcmp($ida, $idb);
|
||||
});
|
||||
return $enabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 ID 从档位列表中取出指定档位;未找到返回 null
|
||||
*/
|
||||
public static function findById(array $items, string $id): ?array
|
||||
{
|
||||
foreach ($items as $row) {
|
||||
if (!is_array($row)) {
|
||||
continue;
|
||||
}
|
||||
$rid = $row['id'] ?? '';
|
||||
if (is_string($rid) && $rid === $id) {
|
||||
return $row;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据语言选择档位对外展示的 title/desc。
|
||||
*
|
||||
* @param array<string, mixed> $item
|
||||
* @return array{title: string, desc: string}
|
||||
*/
|
||||
public static function localize(array $item, string $lang): array
|
||||
{
|
||||
$title = self::stringField($item, 'title');
|
||||
$titleEn = self::stringField($item, 'title_en');
|
||||
$desc = self::stringField($item, 'desc');
|
||||
$descEn = self::stringField($item, 'desc_en');
|
||||
|
||||
$isEn = self::isEnglishLang($lang);
|
||||
$pickedTitle = $isEn ? ($titleEn !== '' ? $titleEn : $title) : ($title !== '' ? $title : $titleEn);
|
||||
$pickedDesc = $isEn ? ($descEn !== '' ? $descEn : $desc) : ($desc !== '' ? $desc : $descEn);
|
||||
|
||||
return [
|
||||
'title' => $pickedTitle,
|
||||
'desc' => $pickedDesc,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成 10 位稳定 ID(t_ + 8 位随机 base32)
|
||||
*/
|
||||
public static function generateId(): string
|
||||
{
|
||||
$chars = 'abcdefghijkmnpqrstuvwxyz23456789';
|
||||
$len = strlen($chars);
|
||||
$id = 't_';
|
||||
for ($i = 0; $i < 8; $i++) {
|
||||
$id .= $chars[random_int(0, $len - 1)];
|
||||
}
|
||||
return $id;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将金额归一化为 4 位小数字符串;非法输入返回 '0.0000'
|
||||
*/
|
||||
public static function normalizeAmount($raw): string
|
||||
{
|
||||
if ($raw === null || $raw === '') {
|
||||
return '0.0000';
|
||||
}
|
||||
if (is_string($raw)) {
|
||||
$s = trim($raw);
|
||||
} elseif (is_int($raw) || is_float($raw)) {
|
||||
$s = strval($raw);
|
||||
} else {
|
||||
return '0.0000';
|
||||
}
|
||||
$s = str_replace(',', '.', $s);
|
||||
if (!is_numeric($s)) {
|
||||
return '0.0000';
|
||||
}
|
||||
return bcadd($s, '0', 4);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从数组取字符串字段并 trim,非字符串返回空串
|
||||
*
|
||||
* @param array<string, mixed> $row
|
||||
*/
|
||||
private static function stringField(array $row, string $key): string
|
||||
{
|
||||
if (!isset($row[$key])) {
|
||||
return '';
|
||||
}
|
||||
$v = $row[$key];
|
||||
return is_string($v) ? trim($v) : '';
|
||||
}
|
||||
|
||||
private static function isEnglishLang(string $lang): bool
|
||||
{
|
||||
$normalized = strtolower(str_replace('_', '-', trim($lang)));
|
||||
if ($normalized === '') {
|
||||
return false;
|
||||
}
|
||||
return $normalized === 'en' || str_starts_with($normalized, 'en-');
|
||||
}
|
||||
}
|
||||
@@ -16,12 +16,10 @@ class BetOrder extends Model
|
||||
'create_time' => 'integer',
|
||||
'update_time' => 'integer',
|
||||
'pick_numbers' => 'json',
|
||||
'unit_amount' => 'string',
|
||||
'total_amount' => 'string',
|
||||
'win_amount' => 'string',
|
||||
'jackpot_extra_amount' => 'string',
|
||||
'status' => 'integer',
|
||||
'pick_count' => 'integer',
|
||||
'streak_at_bet' => 'integer',
|
||||
'is_auto' => 'integer',
|
||||
];
|
||||
|
||||
@@ -42,7 +42,8 @@ class User extends Model
|
||||
'update_time' => 'integer',
|
||||
'coin' => 'string',
|
||||
'total_deposit_coin' => 'string',
|
||||
'total_valid_bet_coin' => 'string',
|
||||
'total_withdraw_coin' => 'string',
|
||||
'bet_flow_coin' => 'string',
|
||||
'risk_flags' => 'integer',
|
||||
'current_streak' => 'integer',
|
||||
];
|
||||
|
||||
@@ -56,6 +56,9 @@ final class GameBetSettleService
|
||||
continue;
|
||||
}
|
||||
|
||||
// 结算刚刚成功(status 1 → 2):把本单下注总额 1:1 累加到用户打码量
|
||||
self::creditUserBetFlow($bet, $now);
|
||||
|
||||
if (bccomp($win, '0', 4) <= 0) {
|
||||
continue;
|
||||
}
|
||||
@@ -106,7 +109,7 @@ final class GameBetSettleService
|
||||
}
|
||||
|
||||
/**
|
||||
* 单注应付派彩:命中开奖号码时 unit × (连胜+1) × 33(与 GameLiveService 一致)。
|
||||
* 应付派彩:开奖号码 ∈ pick_numbers 即中奖;整笔 total_amount × (连胜+1) × 33(与 GameLiveService 一致)。
|
||||
*/
|
||||
public static function computeWinAmount(array $bet, int $resultNumber): string
|
||||
{
|
||||
@@ -121,11 +124,41 @@ final class GameBetSettleService
|
||||
if (!in_array($resultNumber, array_map('intval', $pickNumbers), true)) {
|
||||
return '0.0000';
|
||||
}
|
||||
$unit = (string) ($bet['unit_amount'] ?? '0');
|
||||
$total = (string) ($bet['total_amount'] ?? '0');
|
||||
$streak = (int) ($bet['streak_at_bet'] ?? 0);
|
||||
$odds = (string) (($streak + 1) * self::BASE_ODDS);
|
||||
|
||||
return bcmul($unit, $odds, 4);
|
||||
return bcmul($total, $odds, 4);
|
||||
}
|
||||
|
||||
/**
|
||||
* 累加玩家打码量(流水):按本注单 total_amount 1:1 加到 user.bet_flow_coin。
|
||||
*
|
||||
* 幂等性由调用点保证:只有 bet_order 首次从 status=1 变更为 status=2(返回 $affected=1)
|
||||
* 时才会调用本方法,重复结算不会触发。
|
||||
*/
|
||||
private static function creditUserBetFlow(array $bet, int $now): void
|
||||
{
|
||||
$userId = isset($bet['user_id']) && is_numeric($bet['user_id']) ? intval($bet['user_id']) : 0;
|
||||
if ($userId <= 0) {
|
||||
return;
|
||||
}
|
||||
$totalRaw = $bet['total_amount'] ?? '0';
|
||||
$total = is_string($totalRaw) ? trim($totalRaw) : (is_numeric($totalRaw) ? strval($totalRaw) : '0');
|
||||
if ($total === '' || !is_numeric($total)) {
|
||||
return;
|
||||
}
|
||||
$flow = bcadd($total, '0', 4);
|
||||
if (bccomp($flow, '0', 4) <= 0) {
|
||||
return;
|
||||
}
|
||||
// 原子加法:避免读-改-写导致的并发覆盖;$flow 已由 bcadd 归一化为纯数字字符串,不存在 SQL 注入
|
||||
Db::name('user')
|
||||
->where('id', $userId)
|
||||
->update([
|
||||
'bet_flow_coin' => Db::raw('bet_flow_coin + ' . $flow),
|
||||
'update_time' => $now,
|
||||
]);
|
||||
}
|
||||
|
||||
private static function creditUserPayout(array $bet, int $betId, string $winAmount, int $now): void
|
||||
|
||||
@@ -89,7 +89,6 @@ final class GameLiveService
|
||||
'user_id' => (int) $row['user_id'],
|
||||
'period_no' => (string) $row['period_no'],
|
||||
'pick_numbers' => $row['pick_numbers'],
|
||||
'unit_amount' => (string) $row['unit_amount'],
|
||||
'total_amount' => (string) $row['total_amount'],
|
||||
'streak_at_bet' => (int) $row['streak_at_bet'],
|
||||
'create_time' => (int) $row['create_time'],
|
||||
@@ -303,10 +302,10 @@ final class GameLiveService
|
||||
if (!in_array($number, array_map('intval', $pickNumbers), true)) {
|
||||
continue;
|
||||
}
|
||||
$unit = (string) ($bet['unit_amount'] ?? '0');
|
||||
$total = (string) ($bet['total_amount'] ?? '0');
|
||||
$streak = (int) ($bet['streak_at_bet'] ?? 0);
|
||||
$odds = (string) (($streak + 1) * self::BASE_ODDS);
|
||||
$orderPayout = bcmul($unit, $odds, 4);
|
||||
$orderPayout = bcmul($total, $odds, 4);
|
||||
$payout = bcadd($payout, $orderPayout, 4);
|
||||
}
|
||||
return $payout;
|
||||
|
||||
@@ -82,7 +82,7 @@ final class GameRecordStatService
|
||||
}
|
||||
|
||||
/**
|
||||
* 与 GameLiveService::estimateLossForNumber 中单注派彩一致:命中号码时 unit × (streak+1) × 33。
|
||||
* 与 GameLiveService::estimateLossForNumber 中派彩一致:命中号码时 total_amount × (streak+1) × 33。
|
||||
*/
|
||||
private static function estimatePayoutForBet(array $bet, int $resultNumber): string
|
||||
{
|
||||
@@ -97,10 +97,10 @@ final class GameRecordStatService
|
||||
if (!in_array($resultNumber, array_map('intval', $pickNumbers), true)) {
|
||||
return '0.0000';
|
||||
}
|
||||
$unit = (string) ($bet['unit_amount'] ?? '0');
|
||||
$total = (string) ($bet['total_amount'] ?? '0');
|
||||
$streak = (int) ($bet['streak_at_bet'] ?? 0);
|
||||
$odds = (string) (($streak + 1) * self::BASE_ODDS);
|
||||
|
||||
return bcmul($unit, $odds, 4);
|
||||
return bcmul($total, $odds, 4);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user