SuperballActivityService.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  1. <?php
  2. namespace App\Services;
  3. use App\Facade\TableName;
  4. use App\Game\Services\OuroGameService;
  5. use App\Http\helper\NumConfig;
  6. use Carbon\Carbon;
  7. use Illuminate\Database\QueryException;
  8. use Illuminate\Support\Facades\DB;
  9. use Illuminate\Support\Facades\Redis;
  10. use App\Services\VipService;
  11. /**
  12. * Superball Activity: recharge + turnover task, balls, lucky number, prize pool.
  13. * All amounts in internal units (NUM_VALUE) where needed for DB/score.
  14. */
  15. class SuperballActivityService
  16. {
  17. public const TIER_MAX = 'S';
  18. public const MULTIPLIER_MIN = 1.0;
  19. public const MULTIPLIER_MAX = 3.0;
  20. public const MULTIPLIER_STEP = 0.5;
  21. public const LUCKY_REWARD_PER_BALL = 10; // display unit per matching ball
  22. /**
  23. * Get full activity info: yesterday data, today data, tiers, user task, multiplier.
  24. */
  25. public function getInfo(int $userId): array
  26. {
  27. $today = Carbon::today()->format('Y-m-d');
  28. $yesterday = Carbon::yesterday()->format('Y-m-d');
  29. $tiers = $this->getTierConfig();
  30. $yesterdayDaily = $this->getOrCreateDaily($yesterday);
  31. $todayDaily = $this->getOrCreateDaily($today);
  32. $userTask = $this->getUserTask($userId, $today);
  33. $multiplierRow = $this->getUserMultiplier($userId);
  34. // VIP 等级与每日免费球数(赠送球数 = VIP 等级)
  35. $vipLevel = $this->getUserVipLevel($userId);
  36. $level = VipService::getVipByField('VIP', $vipLevel);
  37. $vipFreeBalls = $level ? ($level->SuperballNum ?? 0) : 0;
  38. $rechargeToday = $this->getUserRechargeForDate($userId, $today);
  39. $turnoverToday = $this->getUserTotalBetForDate($userId, $today);
  40. $turnoverProgress = (int) $turnoverToday;
  41. $tierConfig = $userTask ? $this->getTierConfigByTier($userTask->tier) : null;
  42. $rechargeRequired = $tierConfig ? (int) $tierConfig->recharge_required : 0;
  43. $turnoverRequired = $tierConfig ? (int) $tierConfig->turnover_required : 0;
  44. $rechargeDisplay = $rechargeToday;
  45. $turnoverDisplay = $turnoverProgress / NumConfig::NUM_VALUE;
  46. $taskCompleted = $tierConfig && $rechargeDisplay >= $rechargeRequired && $turnoverDisplay >= $turnoverRequired;
  47. $canClaim = $taskCompleted && $userTask && (int) $userTask->status === 0;
  48. $canUpgrade = $userTask && $userTask->tier !== self::TIER_MAX && $taskCompleted;
  49. // 能升级自动升
  50. if ($canUpgrade && $userTask->status != 1) {
  51. $tierConfigs = $this->getTierConfig();
  52. $up = null;
  53. foreach (array_reverse($tierConfigs) as $c) {
  54. // 已经是最大的档位,直接升级
  55. if ($c['tier'] == self::TIER_MAX
  56. && $c['recharge_required'] < $rechargeToday && $c['turnover_required'] < $turnoverDisplay) {
  57. $up = $c;
  58. break;
  59. }
  60. if ($c['recharge_required'] < $rechargeToday && $c['turnover_required'] < $turnoverDisplay) {
  61. continue;
  62. }
  63. $up = $c;
  64. break;
  65. }
  66. $res = $this->upgradeTier($userId, $up['tier']);
  67. if ($res['success']) {
  68. $tierConfig = $this->getTierConfigByTier($res['new_tier']);
  69. $userTask = $this->getUserTask($userId, $today);
  70. $rechargeRequired = $tierConfig ? (int) $tierConfig->recharge_required : 0;
  71. $turnoverRequired = $tierConfig ? (int) $tierConfig->turnover_required : 0;
  72. $taskCompleted = $tierConfig && $rechargeDisplay >= $rechargeRequired && $turnoverDisplay >= $turnoverRequired;
  73. $canClaim = $taskCompleted && $userTask && (int) $userTask->status === 0;
  74. }
  75. }
  76. $yesterdayBalls = $this->getUserBalls($userId, $yesterday);
  77. $yesterdayLucky = (int) ($yesterdayDaily->lucky_number ?? 0);
  78. $yesterdayPrizeLog = $this->getUserPrizeLog($userId, $yesterday);
  79. $yesterdayBasePerBall = 0;
  80. if ($yesterdayDaily->total_balls > 0 && $yesterdayDaily->pool_amount > 0) {
  81. $yesterdayBasePerBall = (int) ($yesterdayDaily->pool_amount / $yesterdayDaily->total_balls);
  82. }
  83. $yesterdayMyPrize = $yesterdayPrizeLog ? (int) $yesterdayPrizeLog->total_amount : 0;
  84. $yesterdayMultiplier = $yesterdayPrizeLog ? (float) $yesterdayPrizeLog->multiplier : 1.0;
  85. $canClaimYesterday = false;
  86. $yesterdayPendingPrize = 0;
  87. if (!$yesterdayPrizeLog && count($yesterdayBalls) > 0) {
  88. $canClaimYesterday = true;
  89. $yesterdayPendingPrize = $this->calculateYesterdayPrizeForUser($userId, $yesterday);
  90. }
  91. // 用户昨日未领取球
  92. $yesterdayNotClaimedBallCount = $this->getNotClaimBallByUserIdDate($userId, $yesterday);
  93. $todayBasePerBall = 0;
  94. if ($todayDaily->total_balls > 0 && $todayDaily->pool_amount > 0) {
  95. $todayBasePerBall = (int) ($todayDaily->pool_amount / $todayDaily->total_balls);
  96. }
  97. $todayBalls = $this->getUserBalls($userId, $today);
  98. $todayMyBallsList = array_map(function ($b) {
  99. return ['ball_index' => (int) $b->ball_index, 'number' => (int) $b->number];
  100. }, $todayBalls);
  101. $todayNumberCounts = [];
  102. foreach ($todayBalls as $b) {
  103. $n = (int) $b->number;
  104. $todayNumberCounts[$n] = ($todayNumberCounts[$n] ?? 0) + 1;
  105. }
  106. // 0 点到 1 点前,前端展示的今日整体数据全部置为 0(不影响实际统计与任务进度)
  107. $hour = (int) Carbon::now()->format('G'); // 0-23
  108. if ($hour < 1) {
  109. $todayDisplayPoolAmount = 0;
  110. $todayDisplayCompleted = 0;
  111. $todayDisplayTotalBalls = 0;
  112. $todayDisplayBasePerBall = 0;
  113. $todayDisplayMyBalls = $todayMyBallsList;
  114. $todayDisplayNumberCounts = $todayNumberCounts;
  115. } else {
  116. $todayDisplayPoolAmount = (int) $todayDaily->pool_amount;
  117. $todayDisplayCompleted = (int) ($todayDaily->completed_count ?? 0);
  118. $todayDisplayTotalBalls = (int) ($todayDaily->total_balls ?? 0);
  119. $todayDisplayBasePerBall = $todayBasePerBall;
  120. $todayDisplayMyBalls = $todayMyBallsList;
  121. $todayDisplayNumberCounts = $todayNumberCounts;
  122. }
  123. $last7Lucky = $this->getLast7DaysLuckyNumbersPrivate();
  124. $data = [
  125. 'yesterday' => [
  126. 'pool_amount' => (int) $yesterdayDaily->pool_amount,
  127. 'pool_amount_display' => (int) $yesterdayDaily->pool_amount / NumConfig::NUM_VALUE,
  128. 'base_reward_per_ball' => $yesterdayBasePerBall,
  129. 'base_reward_per_ball_display' => $yesterdayBasePerBall / NumConfig::NUM_VALUE,
  130. 'lucky_number' => $yesterdayLucky,
  131. 'completed_count' => (int) ($yesterdayDaily->completed_count ?? 0),
  132. 'total_balls' => (int) ($yesterdayDaily->total_balls ?? 0),
  133. 'my_balls' => $yesterdayBalls,
  134. 'my_balls_with_lucky' => array_map(function ($b) use ($yesterdayLucky) {
  135. return ['number' => (int) $b->number, 'is_lucky' => (int) $b->number === $yesterdayLucky];
  136. }, $yesterdayBalls),
  137. 'my_prize' => $yesterdayPendingPrize, // 临时改下 前端改好了换成 $yesterdayMyPrize
  138. 'my_prize_display' => $yesterdayMyPrize / NumConfig::NUM_VALUE,
  139. 'my_multiplier' => $yesterdayMultiplier,
  140. 'can_claim_yesterday' => $canClaimYesterday,
  141. 'pending_prize' => $yesterdayPendingPrize,
  142. 'pending_prize_display' => $yesterdayPendingPrize / NumConfig::NUM_VALUE,
  143. 'yesterday_not_claimed_ball_count' => $yesterdayNotClaimedBallCount,
  144. ],
  145. 'today' => [
  146. 'pool_amount' => $todayDisplayPoolAmount,
  147. 'pool_amount_display' => $todayDisplayPoolAmount / NumConfig::NUM_VALUE,
  148. 'completed_count' => $todayDisplayCompleted,
  149. 'total_balls' => $todayDisplayTotalBalls,
  150. 'base_reward_per_ball' => $todayDisplayBasePerBall,
  151. 'base_reward_per_ball_display' => $todayDisplayBasePerBall / NumConfig::NUM_VALUE,
  152. 'my_balls' => $todayDisplayMyBalls,
  153. 'number_counts' => $todayDisplayNumberCounts,
  154. ],
  155. 'tiers' => $tiers,
  156. 'user_task' => $userTask ? [
  157. 'tier' => $userTask->tier,
  158. 'recharge_required' => $rechargeRequired,
  159. 'turnover_required' => $turnoverRequired,
  160. 'recharge_progress' => $rechargeDisplay,
  161. 'turnover_progress' => $turnoverDisplay,
  162. 'task_completed' => $taskCompleted,
  163. 'status' => (int) $userTask->status,
  164. 'can_claim' => $canClaim,
  165. 'can_upgrade' => $canUpgrade,
  166. 'ball_count' => $tierConfig ? (int) $tierConfig->ball_count : 0,
  167. ] : null,
  168. 'multiplier' => [
  169. 'value' => (float) ($multiplierRow->multiplier ?? 1.0),
  170. 'consecutive_days' => (int) ($multiplierRow->consecutive_days ?? 0),
  171. 'min' => self::MULTIPLIER_MIN,
  172. 'max' => self::MULTIPLIER_MAX,
  173. 'step' => self::MULTIPLIER_STEP,
  174. ],
  175. 'vip' => [
  176. 'level' => $vipLevel,
  177. 'daily_free_balls' => $vipFreeBalls,
  178. ],
  179. 'lucky_reward_per_ball' => self::LUCKY_REWARD_PER_BALL,
  180. 'lucky_numbers_7_days' => $last7Lucky,
  181. 'can_sumbit' => count($todayDisplayMyBalls) < $vipFreeBalls + ($taskCompleted ? $tierConfig->ball_count : 0)
  182. ];
  183. return $data;
  184. }
  185. /**
  186. * 获取用户 VIP 等级(用于每日赠送球数计算)
  187. */
  188. protected function getUserVipLevel(int $userId): int
  189. {
  190. if ($userId <= 0) {
  191. return 0;
  192. }
  193. // 从 YN_VIPAccount 读取累计充值金额,交由 VipService 计算 VIP 等级
  194. $userRecharge = (int) DB::table('QPAccountsDB.dbo.YN_VIPAccount')
  195. ->where('UserID', $userId)
  196. ->value('Recharge');
  197. return (int) VipService::calculateVipLevel($userId, $userRecharge);
  198. }
  199. /**
  200. * Select task tier for today (with optional confirm). Creates or updates user task.
  201. * @return array success: ['success' => true] | failure: ['success' => false, 'message' => ['key', 'fallback']]
  202. */
  203. public function selectTier(int $userId, string $tier): array
  204. {
  205. $today = Carbon::today()->format('Y-m-d');
  206. $config = $this->getTierConfigByTier($tier);
  207. if (!$config) {
  208. return ['success' => false, 'message' => ['web.superball.activity_not_found', 'Activity not found']];
  209. }
  210. $existing = $this->getUserTask($userId, $today);
  211. if ($existing) {
  212. return ['success' => false, 'message' => ['web.superball.tier_already_selected', 'Already selected tier for today']];
  213. }
  214. DB::connection('write')->table(TableName::agent() . 'superball_user_task')->insert([
  215. 'user_id' => $userId,
  216. 'task_date' => $today,
  217. 'tier' => $tier,
  218. 'total_bet_snapshot' => 0,
  219. 'status' => 0,
  220. 'created_at' => now()->format('Y-m-d H:i:s'),
  221. 'updated_at' => now()->format('Y-m-d H:i:s'),
  222. ]);
  223. return ['success' => true];
  224. }
  225. /**
  226. * Upgrade to higher tier (keep progress). Only allowed when task completed and not A.
  227. * @return array success: ['success' => true] | failure: ['success' => false, 'message' => [...]]
  228. */
  229. public function upgradeTier(int $userId, string $newTier): array
  230. {
  231. $today = Carbon::today()->format('Y-m-d');
  232. $task = $this->getUserTask($userId, $today);
  233. if (!$task) {
  234. return ['success' => false, 'message' => ['web.superball.no_task_today', 'No task for today']];
  235. }
  236. if ((int) $task->status === 1) {
  237. return ['success' => false, 'message' => ['web.superball.already_claimed', 'Already claimed']];
  238. }
  239. $tierOrder = ['E' => 1, 'D' => 2, 'C' => 3, 'B' => 4, 'A' => 5, 'S' => 6];
  240. $currentOrder = $tierOrder[$task->tier] ?? 0;
  241. $newOrder = $tierOrder[$newTier] ?? 0;
  242. if ($newOrder <= $currentOrder) {
  243. return ['success' => false, 'message' => ['web.superball.cannot_downgrade', 'Can only upgrade to higher tier']];
  244. }
  245. $rechargeToday = $this->getUserRechargeForDate($userId, $today);
  246. $turnoverToday = $this->getUserTotalBetForDate($userId, $today);
  247. $newConfig = $this->getTierConfigByTier($task->tier);
  248. $rechargeOk = $rechargeToday >= (int) $newConfig->recharge_required;
  249. $turnoverOk = ($turnoverToday / NumConfig::NUM_VALUE) >= (int) $newConfig->turnover_required;
  250. // var_dump($rechargeToday,$turnoverToday,$newConfig);
  251. if (!$rechargeOk || !$turnoverOk) {
  252. return ['success' => false, 'message' => ['web.superball.task_not_completed', 'Task not completed']];
  253. }
  254. DB::connection('write')->table(TableName::agent() . 'superball_user_task')
  255. ->where('user_id', $userId)
  256. ->where('task_date', $today)
  257. ->update(['tier' => $newTier, 'updated_at' => now()->format('Y-m-d H:i:s')]);
  258. return ['success' => true,'user_id' => $userId, 'new_tier' => $newTier,'task_date'=>$today];
  259. }
  260. /**
  261. * Claim reward: grant balls, update daily total_balls/completed_count, update multiplier, mark task claimed.
  262. * @return array success: ['ball_count' => n, 'message' => ...] | failure: ['success' => false, 'message' => [...]]
  263. */
  264. public function claimReward(int $userId): array
  265. {
  266. $today = Carbon::today()->format('Y-m-d');
  267. $task = $this->getUserTask($userId, $today);
  268. $vipLevel = $this->getUserVipLevel($userId);
  269. $level = VipService::getVipByField('VIP', $vipLevel);
  270. $vipFreeBalls = $level ? ($level->SuperballNum ?? 0) : 0;
  271. if (!$task) {
  272. // 昨日未领取奖励
  273. $yesterday = Carbon::yesterday()->format('Y-m-d');
  274. $yesterdayBallCount = $this->getNotClaimBallByUserIdDate($userId, $yesterday);
  275. if ($yesterdayBallCount > 0) {
  276. $vipFreeBalls += $yesterdayBallCount;
  277. }
  278. $this->claimIfHasVipReward($userId, $vipFreeBalls);
  279. $this->selectTier($userId, 'E');
  280. return [
  281. 'ball_count' => $vipFreeBalls,
  282. 'base_ball_count' => 0,
  283. 'vip_free_balls' => $vipFreeBalls,
  284. 'message' => 'Claim success, please select numbers for your balls',
  285. ];
  286. }
  287. if ((int) $task->status === 1) {
  288. return ['success' => false, 'message' => ['web.superball.already_claimed', 'Already claimed']];
  289. }
  290. $tierConfig = $this->getTierConfigByTier($task->tier);
  291. if (!$tierConfig) {
  292. return ['success' => false, 'message' => ['web.superball.activity_not_found', 'Activity not found']];
  293. }
  294. $rechargeToday = $this->getUserRechargeForDate($userId, $today);
  295. $turnoverToday = $this->getUserTotalBetForDate($userId, $today);
  296. $rechargeOk = ($rechargeToday) >= (int) $tierConfig->recharge_required;
  297. $turnoverOk = ($turnoverToday / NumConfig::NUM_VALUE) >= (int) $tierConfig->turnover_required;
  298. $complete = 1;
  299. if (!$rechargeOk || !$turnoverOk) {
  300. // 本档没完成
  301. $complete = 0;
  302. }
  303. // 所有任务累加
  304. $tierConfigs = $this->getTierConfig();
  305. $ballCount = 0;
  306. foreach ($tierConfigs as $config) {
  307. if ($config['sort_index'] < $tierConfig->sort_index) {
  308. continue;
  309. }
  310. if ($config['recharge_required'] <= $rechargeToday && $config['turnover_required'] <= ($turnoverToday / NumConfig::NUM_VALUE)) {
  311. $ballCount += (int) $config['ball_count'];
  312. }
  313. }
  314. if ($ballCount < 1) {
  315. return ['success' => false, 'message' => ['web.superball.task_not_completed', 'Task not completed']];
  316. }
  317. DB::connection('write')->transaction(function () use ($userId, $today, $task, $ballCount, $complete) {
  318. DB::connection('write')->table(TableName::agent() . 'superball_user_task')
  319. ->where('user_id', $userId)
  320. ->where('task_date', $today)
  321. ->update(['status' => 1, 'complete' => $complete, 'updated_at' => now()->format('Y-m-d H:i:s')]);
  322. DB::connection('write')->table(TableName::agent() . 'superball_daily')
  323. ->where('pool_date', $today)
  324. ->update([
  325. 'total_balls' => DB::raw('total_balls+' . $ballCount),
  326. 'completed_count' => DB::raw('completed_count+1'),
  327. 'updated_at' => now()->format('Y-m-d H:i:s'),
  328. ]);
  329. $this->updateUserMultiplier($userId, $today);
  330. });
  331. return [
  332. 'ball_count' => $ballCount,
  333. 'base_ball_count' => $ballCount,
  334. 'vip_free_balls' => $vipFreeBalls,
  335. 'message' => 'Claim success, please select numbers for your balls',
  336. ];
  337. }
  338. public function claimIfHasVipReward(int $userId, $vipFreeBalls): bool
  339. {
  340. $key = sprintf('claim_vip_reward_%s_%s', $userId, date('Ymd'));
  341. if (Redis::exists($key)) {
  342. return false;
  343. }
  344. $today = Carbon::today()->format('Y-m-d');
  345. DB::connection('write')->table(TableName::agent() . 'superball_daily')
  346. ->where('pool_date', $today)
  347. ->update([
  348. 'total_balls' => DB::raw('total_balls+' . $vipFreeBalls),
  349. 'updated_at' => now()->format('Y-m-d H:i:s'),
  350. ]);
  351. Redis::set($key, $vipFreeBalls);
  352. Redis::expire($key, 86400);
  353. return true;
  354. }
  355. /**
  356. * Submit numbers for all balls (0-9 per ball). Must have claimed and not yet submitted.
  357. * @return array success: ['success' => true] | failure: ['success' => false, 'message' => [...]]
  358. */
  359. public function submitNumbers(int $userId, array $numbers): array
  360. {
  361. $key = sprintf('claim_vip_reward_%s_%s', $userId, date('Ymd'));
  362. $vipFreeBalls = (int) Redis::get($key);
  363. $vipLevel = $this->getUserVipLevel($userId);
  364. $level = VipService::getVipByField('VIP', $vipLevel);
  365. $vipFreeBalls2 = $level ? ($level->SuperballNum ?? 0) : 0;
  366. $vipFreeBalls = max($vipFreeBalls, $vipFreeBalls2);
  367. $today = Carbon::today()->format('Y-m-d');
  368. $task = $this->getUserTask($userId, $today);
  369. $ballCount = 0;
  370. $tierConfig = $this->getTierConfigByTier($task->tier);
  371. $rechargeToday = $this->getUserRechargeForDate($userId, $today);
  372. $turnoverToday = $this->getUserTotalBetForDate($userId, $today);
  373. if ($task && $task->status == 1) {
  374. $tierConfigs = $this->getTierConfig();
  375. foreach ($tierConfigs as $config) {
  376. if ($config['sort_index'] < $tierConfig->sort_index) {
  377. continue;
  378. }
  379. if ($config['recharge_required'] <= $rechargeToday && $config['turnover_required'] <= ($turnoverToday / NumConfig::NUM_VALUE)) {
  380. $ballCount += (int) $config['ball_count'];
  381. }
  382. }
  383. }
  384. $existing = DB::connection('write')->table(TableName::agent() . 'superball_user_balls')
  385. ->where('user_id', $userId)
  386. ->where('ball_date', $today)
  387. ->count();
  388. // 与领取时保持一致:基础任务球数 + 每日 VIP 免费球数
  389. $ballCount = $ballCount + $vipFreeBalls;
  390. if ($ballCount < 1) {
  391. return ['success' => false, 'message' => ['web.superball.number_count_mismatch', 'no ball']];
  392. }
  393. if (count($numbers) + $existing > $ballCount) {
  394. $remain = $ballCount - $existing;
  395. if ($remain < 1) {
  396. return ['success' => false, 'message' => ['web.superball.number_count_mismatch', 'Number count mismatch']];
  397. }
  398. $numbers = array_slice($numbers, 0, $remain);
  399. }
  400. DB::connection('write')->transaction(function () use ($userId, $today, $numbers) {
  401. // 写入用户今日所有球号
  402. foreach ($numbers as $index => $num) {
  403. $n = (int) $num;
  404. if ($n < 0 || $n > 9) {
  405. throw new \RuntimeException('Number must be 0-9');
  406. }
  407. DB::connection('write')->table(TableName::agent() . 'superball_user_balls')->insert([
  408. 'user_id' => $userId,
  409. 'ball_date' => $today,
  410. 'ball_index' => $index + 1,
  411. 'number' => $n,
  412. 'created_at' => now()->format('Y-m-d H:i:s'),
  413. ]);
  414. }
  415. // 若用户选择的号码等于当日 lucky_number,则把 superball_daily.lucky_count 累加
  416. $daily = DB::connection('write')
  417. ->table(TableName::agent() . 'superball_daily')
  418. ->where('pool_date', $today)
  419. ->first();
  420. if ($daily) {
  421. $luckyNumber = (int) $daily->lucky_number;
  422. $matched = 0;
  423. foreach ($numbers as $num) {
  424. if ((int) $num === $luckyNumber) {
  425. $matched++;
  426. }
  427. }
  428. if ($matched > 0) {
  429. DB::connection('write')
  430. ->table(TableName::agent() . 'superball_daily')
  431. ->where('pool_date', $today)
  432. ->update([
  433. 'lucky_count' => DB::raw("lucky_count + {$matched}"),
  434. 'updated_at' => now()->format('Y-m-d H:i:s'),
  435. ]);
  436. }
  437. }
  438. });
  439. return ['success' => true];
  440. }
  441. /**
  442. * Get user's balls for a date (for number selection page or display).
  443. */
  444. public function getMyBalls(int $userId, string $date): array
  445. {
  446. $rows = DB::table(TableName::agent() . 'superball_user_balls')
  447. ->where('user_id', $userId)
  448. ->where('ball_date', $date)
  449. ->orderBy('ball_index')
  450. ->get();
  451. return array_map(function ($r) {
  452. return ['ball_index' => (int) $r->ball_index, 'number' => (int) $r->number];
  453. }, $rows->all());
  454. }
  455. /**
  456. * User claims yesterday's reward (next-day claim, no auto distribution).
  457. * Formula: base = pool / total_balls * ball_count, lucky = 10 * matched_balls (display), total = base * multiplier + lucky.
  458. * @return array success: data with total_amount etc. | failure: ['success' => false, 'message' => [...]]
  459. */
  460. public function claimYesterdayReward(int $userId): array
  461. {
  462. $yesterday = Carbon::yesterday()->format('Y-m-d');
  463. $existing = $this->getUserPrizeLog($userId, $yesterday);
  464. if ($existing) {
  465. return ['success' => false, 'message' => ['web.superball.yesterday_already_claimed', 'Yesterday reward already claimed']];
  466. }
  467. $balls = $this->getUserBalls($userId, $yesterday);
  468. if (count($balls) === 0) {
  469. return ['success' => false, 'message' => ['web.superball.no_balls_yesterday', 'No balls for yesterday, nothing to claim']];
  470. }
  471. $daily = DB::table(TableName::agent() . 'superball_daily')->where('pool_date', $yesterday)->first();
  472. if (!$daily || (int) $daily->total_balls <= 0) {
  473. return ['success' => false, 'message' => ['web.superball.pool_not_ready', 'Yesterday pool not ready']];
  474. }
  475. $basePerBall = (int) ($daily->pool_amount / $daily->total_balls);
  476. $luckyNumber = (int) $daily->lucky_number;
  477. $multiplierRow = $this->getUserMultiplier($userId);
  478. $multiplier = (float) ($multiplierRow->multiplier ?? 1.0);
  479. // 选号可重复:每个球单独比对幸运号,中奖球数 = 号码等于幸运号的球个数(同一号码可多球)
  480. $matched = 0;
  481. foreach ($balls as $b) {
  482. if ((int) $b->number === $luckyNumber) {
  483. $matched++;
  484. }
  485. }
  486. $baseAmount = $basePerBall * count($balls);
  487. $luckyAmountDisplay = self::LUCKY_REWARD_PER_BALL * $matched;
  488. $luckyAmountInternal = $luckyAmountDisplay * NumConfig::NUM_VALUE;
  489. $totalAmount = (int) round($baseAmount * $multiplier) + $luckyAmountInternal;
  490. DB::connection('write')->table(TableName::agent() . 'superball_prize_log')->insert([
  491. 'user_id' => $userId,
  492. 'settle_date' => $yesterday,
  493. 'base_amount' => $baseAmount,
  494. 'lucky_amount' => $luckyAmountInternal,
  495. 'multiplier' => $multiplier,
  496. 'total_amount' => $totalAmount,
  497. 'created_at' => now()->format('Y-m-d H:i:s'),
  498. ]);
  499. OuroGameService::AddScore($userId, $totalAmount, 90);
  500. return [
  501. 'total_amount' => $totalAmount,
  502. 'total_amount_display' => $totalAmount / NumConfig::NUM_VALUE,
  503. 'base_amount' => $baseAmount,
  504. 'lucky_amount' => $luckyAmountInternal,
  505. 'multiplier' => $multiplier,
  506. ];
  507. }
  508. /**
  509. * Calculate yesterday prize for user (for display only, no claim).
  510. */
  511. public function calculateYesterdayPrizeForUser(int $userId, string $yesterday): int
  512. {
  513. $daily = DB::table(TableName::agent() . 'superball_daily')->where('pool_date', $yesterday)->first();
  514. if (!$daily || (int) $daily->total_balls <= 0) {
  515. return 0;
  516. }
  517. $balls = $this->getUserBalls($userId, $yesterday);
  518. if (count($balls) === 0) {
  519. return 0;
  520. }
  521. $basePerBall = (int) ($daily->pool_amount / $daily->total_balls);
  522. $luckyNumber = (int) $daily->lucky_number;
  523. $multiplierRow = $this->getUserMultiplier($userId);
  524. $multiplier = (float) ($multiplierRow->multiplier ?? 1.0);
  525. // 选号可重复:按球逐个比对幸运号,中奖球数 = 号码等于幸运号的球个数
  526. $matched = 0;
  527. foreach ($balls as $b) {
  528. if ((int) $b->number === $luckyNumber) {
  529. $matched++;
  530. }
  531. }
  532. $baseAmount = $basePerBall * count($balls);
  533. $luckyAmountInternal = self::LUCKY_REWARD_PER_BALL * $matched * NumConfig::NUM_VALUE;
  534. return (int) round($baseAmount * $multiplier) + $luckyAmountInternal;
  535. }
  536. /**
  537. * Get last 7 days lucky numbers (for display).
  538. */
  539. public function getLast7DaysLuckyNumbers(): array
  540. {
  541. return $this->getLast7DaysLuckyNumbersPrivate();
  542. }
  543. /**
  544. * Ensure daily row and lucky number for date (idempotent).
  545. */
  546. public function getOrCreateDaily(string $date): \stdClass
  547. {
  548. $row = DB::table(TableName::agent() . 'superball_daily')->where('pool_date', $date)->first();
  549. if ($row) {
  550. return $row;
  551. }
  552. $lucky = mt_rand(0, 9);
  553. try {
  554. DB::connection('write')->table(TableName::agent() . 'superball_daily')->insert([
  555. 'pool_date' => $date,
  556. 'pool_amount' => 0,
  557. 'total_balls' => 0,
  558. 'lucky_number' => $lucky,
  559. 'completed_count' => 0,
  560. 'lucky_count' => 0,
  561. 'created_at' => now()->format('Y-m-d H:i:s'),
  562. 'updated_at' => now()->format('Y-m-d H:i:s'),
  563. ]);
  564. } catch (QueryException $e) {
  565. // Concurrent getOrCreateDaily: unique index IX_superball_daily_date (pool_date)
  566. if (stripos($e->getMessage(), 'duplicate key') === false) {
  567. throw $e;
  568. }
  569. }
  570. return DB::table(TableName::agent() . 'superball_daily')->where('pool_date', $date)->first();
  571. }
  572. /**
  573. * Update pool amount for a date (call from job that aggregates daily turnover).
  574. */
  575. public function updatePoolAmount(string $date, int $poolAmountInternal): void
  576. {
  577. DB::connection('write')->table(TableName::agent() . 'superball_daily')
  578. ->where('pool_date', $date)
  579. ->update(['pool_amount' => $poolAmountInternal, 'updated_at' => now()->format('Y-m-d H:i:s')]);
  580. }
  581. /**
  582. * 获取某天未领取的球数
  583. * @param $userId
  584. * @param $date
  585. * @return int
  586. */
  587. public function getNotClaimBallByUserIdDate($userId, $date) :int
  588. {
  589. $cacheKey = sprintf('superball_yesterday_not_claim_%d_%s', $userId, $date);
  590. if (Redis::exists($cacheKey)) {
  591. $ball = Redis::get($cacheKey);
  592. return (int) $ball;
  593. }
  594. $ball = 0;
  595. $task = $this->getUserTask($userId, $date);
  596. if (!$task || $task->status == 0) {
  597. $recharge = $this->getUserRechargeForDate($userId, $date);
  598. $turnover = $this->getUserTotalBetForDate($userId, $date) / NumConfig::NUM_VALUE;
  599. $configs = $this->getTierConfig();
  600. foreach ($configs as $config) {
  601. if ($recharge >= $config['recharge_required'] && $turnover >= $config['turnover_required']) {
  602. $ball += $config['ball_count'];
  603. }
  604. }
  605. }
  606. Redis::set($cacheKey, $ball);
  607. Redis::expireAt($cacheKey, strtotime('today +1 day'));
  608. return $ball;
  609. }
  610. // --- private helpers ---
  611. private function getTierConfig(): array
  612. {
  613. $rows = DB::table(TableName::agent() . 'superball_tier_config')
  614. ->orderBy('sort_index')
  615. ->get();
  616. return array_map(function ($r) {
  617. return [
  618. 'sort_index' => $r->sort_index,
  619. 'tier' => $r->tier,
  620. 'recharge_required' => (int) $r->recharge_required,
  621. 'turnover_required' => (int) $r->turnover_required,
  622. 'ball_count' => (int) $r->ball_count,
  623. ];
  624. }, $rows->all());
  625. }
  626. private function getTierConfigByTier(string $tier): ?\stdClass
  627. {
  628. return DB::table(TableName::agent() . 'superball_tier_config')->where('tier', $tier)->first();
  629. }
  630. private function getUserTask(int $userId, string $date): ?\stdClass
  631. {
  632. return DB::table(TableName::agent() . 'superball_user_task')
  633. ->where('user_id', $userId)
  634. ->where('task_date', $date)
  635. ->first();
  636. }
  637. private function getUserRechargeForDate(int $userId, string $date): int
  638. {
  639. $dateId = str_replace('-', '', $date);
  640. $row = DB::table(TableName::QPRecordDB() . 'RecordUserDataStatisticsNew')
  641. ->where('UserID', $userId)
  642. ->where('DateID', $dateId)
  643. ->first();
  644. return $row ? (int) $row->Recharge : 0;
  645. }
  646. /** 当日流水:从按日统计表取当天 TotalBet(内部单位) */
  647. private function getUserTotalBetForDate(int $userId, string $date): int
  648. {
  649. $dateId = str_replace('-', '', $date);
  650. $row = DB::table(TableName::QPRecordDB() . 'RecordUserDataStatisticsNew')
  651. ->where('UserID', $userId)
  652. ->where('DateID', $dateId)
  653. ->first();
  654. return $row && isset($row->TotalBet) ? (int) $row->TotalBet : 0;
  655. }
  656. private function getUserTotalBet(int $userId): int
  657. {
  658. $row = DB::table(TableName::QPRecordDB() . 'RecordUserTotalStatistics')
  659. ->where('UserID', $userId)
  660. ->first();
  661. return $row ? (int) $row->TotalBet : 0;
  662. }
  663. private function getUserBalls(int $userId, string $date): array
  664. {
  665. return DB::table(TableName::agent() . 'superball_user_balls')
  666. ->where('user_id', $userId)
  667. ->where('ball_date', $date)
  668. ->orderBy('ball_index')
  669. ->get()
  670. ->all();
  671. }
  672. private function getUserMultiplier(int $userId): ?\stdClass
  673. {
  674. return DB::table(TableName::agent() . 'superball_user_multiplier')->where('user_id', $userId)->first();
  675. }
  676. private function getUserPrizeLog(int $userId, string $date): ?\stdClass
  677. {
  678. return DB::table(TableName::agent() . 'superball_prize_log')
  679. ->where('user_id', $userId)
  680. ->where('settle_date', $date)
  681. ->first();
  682. }
  683. private function getLast7DaysLuckyNumbersPrivate(): array
  684. {
  685. $dates = [];
  686. for ($i = 0; $i < 7; $i++) {
  687. $dates[] = Carbon::today()->subDays($i)->format('Y-m-d');
  688. }
  689. $rows = DB::table(TableName::agent() . 'superball_daily')
  690. ->whereIn('pool_date', $dates)
  691. ->orderBy('pool_date', 'desc')
  692. ->get();
  693. $map = [];
  694. foreach ($rows as $r) {
  695. $map[$r->pool_date] = (int) $r->lucky_number;
  696. }
  697. return array_map(function ($d) use ($map) {
  698. return ['date' => $d, 'lucky_number' => $map[$d] ?? null];
  699. }, $dates);
  700. }
  701. private function updateUserMultiplier(int $userId, string $taskDate): void
  702. {
  703. $row = DB::connection('write')->table(TableName::agent() . 'superball_user_multiplier')
  704. ->where('user_id', $userId)
  705. ->lockForUpdate()
  706. ->first();
  707. $multiplier = self::MULTIPLIER_MIN;
  708. $consecutive = 1;
  709. if ($row) {
  710. $last = $row->last_task_date ? (string) $row->last_task_date : null;
  711. $prev = Carbon::parse($taskDate)->subDay()->format('Y-m-d');
  712. if ($last === $prev) {
  713. $consecutive = (int) $row->consecutive_days + 1;
  714. $multiplier = min(self::MULTIPLIER_MAX, (float) $row->multiplier + self::MULTIPLIER_STEP);
  715. } elseif ($last !== null && $last !== $taskDate) {
  716. $daysDiff = (int) Carbon::parse($taskDate)->diffInDays(Carbon::parse($last));
  717. if ($daysDiff > 1) {
  718. $multiplier = max(self::MULTIPLIER_MIN, (float) $row->multiplier - self::MULTIPLIER_STEP);
  719. $consecutive = 1;
  720. } else {
  721. $multiplier = (float) $row->multiplier;
  722. $consecutive = (int) $row->consecutive_days + 1;
  723. }
  724. }
  725. }
  726. DB::connection('write')->table(TableName::agent() . 'superball_user_multiplier')->updateOrInsert(
  727. ['user_id' => $userId],
  728. [
  729. 'consecutive_days' => $consecutive,
  730. 'last_task_date' => $taskDate,
  731. 'multiplier' => $multiplier,
  732. 'updated_at' => now()->format('Y-m-d H:i:s'),
  733. ]
  734. );
  735. }
  736. }