SuperballActivityService.php 36 KB

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