SuperballActivityService.php 36 KB

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