SuperballActivityService.php 36 KB

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