SuperballActivityService.php 34 KB

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