SuperballActivityService.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  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. ->lock('with(nolock)')
  421. ->where('pool_date', $today)
  422. ->first();
  423. if ($daily) {
  424. $luckyNumber = (int) $daily->lucky_number;
  425. $matched = 0;
  426. foreach ($numbers as $num) {
  427. if ((int) $num === $luckyNumber) {
  428. $matched++;
  429. }
  430. }
  431. if ($matched > 0) {
  432. DB::connection('write')
  433. ->table(TableName::agent() . 'superball_daily')
  434. ->where('pool_date', $today)
  435. ->update([
  436. 'lucky_count' => DB::raw("lucky_count + {$matched}"),
  437. 'updated_at' => now()->format('Y-m-d H:i:s'),
  438. ]);
  439. }
  440. }
  441. });
  442. return ['success' => true];
  443. }
  444. /**
  445. * Get user's balls for a date (for number selection page or display).
  446. */
  447. public function getMyBalls(int $userId, string $date): array
  448. {
  449. $rows = DB::table(TableName::agent() . 'superball_user_balls')
  450. ->where('user_id', $userId)
  451. ->where('ball_date', $date)
  452. ->orderBy('ball_index')
  453. ->get();
  454. return array_map(function ($r) {
  455. return ['ball_index' => (int) $r->ball_index, 'number' => (int) $r->number];
  456. }, $rows->all());
  457. }
  458. /**
  459. * User claims yesterday's reward (next-day claim, no auto distribution).
  460. * Formula: base = pool / total_balls * ball_count, lucky = 10 * matched_balls (display), total = base * multiplier + lucky.
  461. * @return array success: data with total_amount etc. | failure: ['success' => false, 'message' => [...]]
  462. */
  463. public function claimYesterdayReward(int $userId): array
  464. {
  465. $yesterday = Carbon::yesterday()->format('Y-m-d');
  466. $existing = $this->getUserPrizeLog($userId, $yesterday);
  467. if ($existing) {
  468. return ['success' => false, 'message' => ['web.superball.yesterday_already_claimed', 'Yesterday reward already claimed']];
  469. }
  470. $balls = $this->getUserBalls($userId, $yesterday);
  471. if (count($balls) === 0) {
  472. return ['success' => false, 'message' => ['web.superball.no_balls_yesterday', 'No balls for yesterday, nothing to claim']];
  473. }
  474. $daily = DB::table(TableName::agent() . 'superball_daily')->where('pool_date', $yesterday)->first();
  475. if (!$daily || (int) $daily->total_balls <= 0) {
  476. return ['success' => false, 'message' => ['web.superball.pool_not_ready', 'Yesterday pool not ready']];
  477. }
  478. $basePerBall = (int) ($daily->pool_amount / $daily->total_balls);
  479. $luckyNumber = (int) $daily->lucky_number;
  480. $multiplierRow = $this->getUserMultiplier($userId);
  481. $multiplier = (float) ($multiplierRow->multiplier ?? 1.0);
  482. // 选号可重复:每个球单独比对幸运号,中奖球数 = 号码等于幸运号的球个数(同一号码可多球)
  483. $matched = 0;
  484. foreach ($balls as $b) {
  485. if ((int) $b->number === $luckyNumber) {
  486. $matched++;
  487. }
  488. }
  489. $baseAmount = $basePerBall * count($balls);
  490. $luckyAmountDisplay = self::LUCKY_REWARD_PER_BALL * $matched;
  491. $luckyAmountInternal = $luckyAmountDisplay * NumConfig::NUM_VALUE;
  492. $totalAmount = (int) round($baseAmount * $multiplier) + $luckyAmountInternal;
  493. DB::connection('write')->table(TableName::agent() . 'superball_prize_log')->insert([
  494. 'user_id' => $userId,
  495. 'settle_date' => $yesterday,
  496. 'base_amount' => $baseAmount,
  497. 'lucky_amount' => $luckyAmountInternal,
  498. 'multiplier' => $multiplier,
  499. 'total_amount' => $totalAmount,
  500. 'created_at' => now()->format('Y-m-d H:i:s'),
  501. ]);
  502. OuroGameService::AddScore($userId, $totalAmount, 90);
  503. return [
  504. 'total_amount' => $totalAmount,
  505. 'total_amount_display' => $totalAmount / NumConfig::NUM_VALUE,
  506. 'base_amount' => $baseAmount,
  507. 'lucky_amount' => $luckyAmountInternal,
  508. 'multiplier' => $multiplier,
  509. ];
  510. }
  511. /**
  512. * Calculate yesterday prize for user (for display only, no claim).
  513. */
  514. public function calculateYesterdayPrizeForUser(int $userId, string $yesterday): int
  515. {
  516. $daily = DB::table(TableName::agent() . 'superball_daily')->where('pool_date', $yesterday)->first();
  517. if (!$daily || (int) $daily->total_balls <= 0) {
  518. return 0;
  519. }
  520. $balls = $this->getUserBalls($userId, $yesterday);
  521. if (count($balls) === 0) {
  522. return 0;
  523. }
  524. $basePerBall = (int) ($daily->pool_amount / $daily->total_balls);
  525. $luckyNumber = (int) $daily->lucky_number;
  526. $multiplierRow = $this->getUserMultiplier($userId);
  527. $multiplier = (float) ($multiplierRow->multiplier ?? 1.0);
  528. // 选号可重复:按球逐个比对幸运号,中奖球数 = 号码等于幸运号的球个数
  529. $matched = 0;
  530. foreach ($balls as $b) {
  531. if ((int) $b->number === $luckyNumber) {
  532. $matched++;
  533. }
  534. }
  535. $baseAmount = $basePerBall * count($balls);
  536. $luckyAmountInternal = self::LUCKY_REWARD_PER_BALL * $matched * NumConfig::NUM_VALUE;
  537. return (int) round($baseAmount * $multiplier) + $luckyAmountInternal;
  538. }
  539. /**
  540. * Get last 7 days lucky numbers (for display).
  541. */
  542. public function getLast7DaysLuckyNumbers(): array
  543. {
  544. return $this->getLast7DaysLuckyNumbersPrivate();
  545. }
  546. /**
  547. * Ensure daily row and lucky number for date (idempotent).
  548. */
  549. public function getOrCreateDaily(string $date): \stdClass
  550. {
  551. $row = DB::table(TableName::agent() . 'superball_daily')->where('pool_date', $date)->first();
  552. if ($row) {
  553. return $row;
  554. }
  555. $lucky = mt_rand(0, 9);
  556. try {
  557. DB::connection('write')->table(TableName::agent() . 'superball_daily')->insert([
  558. 'pool_date' => $date,
  559. 'pool_amount' => 0,
  560. 'total_balls' => 0,
  561. 'lucky_number' => $lucky,
  562. 'completed_count' => 0,
  563. 'lucky_count' => 0,
  564. 'created_at' => now()->format('Y-m-d H:i:s'),
  565. 'updated_at' => now()->format('Y-m-d H:i:s'),
  566. ]);
  567. } catch (QueryException $e) {
  568. // Concurrent getOrCreateDaily: unique index IX_superball_daily_date (pool_date)
  569. if (stripos($e->getMessage(), 'duplicate key') === false) {
  570. throw $e;
  571. }
  572. }
  573. return DB::table(TableName::agent() . 'superball_daily')->where('pool_date', $date)->first();
  574. }
  575. /**
  576. * Update pool amount for a date (call from job that aggregates daily turnover).
  577. */
  578. public function updatePoolAmount(string $date, int $poolAmountInternal): void
  579. {
  580. DB::connection('write')->table(TableName::agent() . 'superball_daily')
  581. ->where('pool_date', $date)
  582. ->update(['pool_amount' => $poolAmountInternal, 'updated_at' => now()->format('Y-m-d H:i:s')]);
  583. }
  584. /**
  585. * 获取某天未领取的球数
  586. * @param $userId
  587. * @param $date
  588. * @return int
  589. */
  590. public function getNotClaimBallByUserIdDate($userId, $date) :int
  591. {
  592. $cacheKey = sprintf('superball_yesterday_not_claim_%d_%s', $userId, $date);
  593. if (Redis::exists($cacheKey)) {
  594. $ball = Redis::get($cacheKey);
  595. return (int) $ball;
  596. }
  597. $ball = 0;
  598. $task = $this->getUserTask($userId, $date);
  599. if ($task && $task->status == 0) {
  600. $config = $this->getTierConfigByTier($task->tier);
  601. if ($task->complete) {
  602. $ball = $config->ball_count;
  603. } else if ($task->tier != 'E') {
  604. $idx = $config->sort_index+1;
  605. $configs = $this->getTierConfig();
  606. foreach ($configs as $config) {
  607. if ($config['sort_index'] == $idx) {
  608. $ball += $config['ball_count'];
  609. }
  610. }
  611. }
  612. }
  613. Redis::set($cacheKey, $ball);
  614. Redis::expireAt($cacheKey, strtotime('today +1 day'));
  615. return $ball;
  616. }
  617. // --- private helpers ---
  618. private function getTierConfig(): array
  619. {
  620. $rows = DB::table(TableName::agent() . 'superball_tier_config')
  621. ->orderBy('sort_index')
  622. ->get();
  623. return array_map(function ($r) {
  624. return [
  625. 'sort_index' => $r->sort_index,
  626. 'tier' => $r->tier,
  627. 'recharge_required' => (int) $r->recharge_required,
  628. 'turnover_required' => (int) $r->turnover_required,
  629. 'ball_count' => (int) $r->ball_count,
  630. ];
  631. }, $rows->all());
  632. }
  633. private function getTierConfigByTier(string $tier): ?\stdClass
  634. {
  635. return DB::table(TableName::agent() . 'superball_tier_config')->where('tier', $tier)->first();
  636. }
  637. private function getUserTask(int $userId, string $date): ?\stdClass
  638. {
  639. return DB::table(TableName::agent() . 'superball_user_task')
  640. ->where('user_id', $userId)
  641. ->where('task_date', $date)
  642. ->first();
  643. }
  644. private function getUserRechargeForDate(int $userId, string $date): int
  645. {
  646. $dateId = str_replace('-', '', $date);
  647. $row = DB::table(TableName::QPRecordDB() . 'RecordUserDataStatisticsNew')
  648. ->where('UserID', $userId)
  649. ->where('DateID', $dateId)
  650. ->first();
  651. return $row ? (int) $row->Recharge : 0;
  652. }
  653. /** 当日流水:从按日统计表取当天 TotalBet(内部单位) */
  654. private function getUserTotalBetForDate(int $userId, string $date): int
  655. {
  656. $dateId = str_replace('-', '', $date);
  657. $row = DB::table(TableName::QPRecordDB() . 'RecordUserDataStatisticsNew')
  658. ->where('UserID', $userId)
  659. ->where('DateID', $dateId)
  660. ->first();
  661. return $row && isset($row->TotalBet) ? (int) $row->TotalBet : 0;
  662. }
  663. private function getUserTotalBet(int $userId): int
  664. {
  665. $row = DB::table(TableName::QPRecordDB() . 'RecordUserTotalStatistics')
  666. ->where('UserID', $userId)
  667. ->first();
  668. return $row ? (int) $row->TotalBet : 0;
  669. }
  670. private function getUserBalls(int $userId, string $date): array
  671. {
  672. return DB::table(TableName::agent() . 'superball_user_balls')
  673. ->where('user_id', $userId)
  674. ->where('ball_date', $date)
  675. ->orderBy('ball_index')
  676. ->get()
  677. ->all();
  678. }
  679. private function getUserMultiplier(int $userId): ?\stdClass
  680. {
  681. return DB::table(TableName::agent() . 'superball_user_multiplier')->where('user_id', $userId)->first();
  682. }
  683. private function getUserPrizeLog(int $userId, string $date): ?\stdClass
  684. {
  685. return DB::table(TableName::agent() . 'superball_prize_log')
  686. ->where('user_id', $userId)
  687. ->where('settle_date', $date)
  688. ->first();
  689. }
  690. private function getLast7DaysLuckyNumbersPrivate(): array
  691. {
  692. $dates = [];
  693. for ($i = 0; $i < 7; $i++) {
  694. $dates[] = Carbon::today()->subDays($i)->format('Y-m-d');
  695. }
  696. $rows = DB::table(TableName::agent() . 'superball_daily')
  697. ->whereIn('pool_date', $dates)
  698. ->orderBy('pool_date', 'desc')
  699. ->get();
  700. $map = [];
  701. foreach ($rows as $r) {
  702. $map[$r->pool_date] = (int) $r->lucky_number;
  703. }
  704. return array_map(function ($d) use ($map) {
  705. return ['date' => $d, 'lucky_number' => $map[$d] ?? null];
  706. }, $dates);
  707. }
  708. private function updateUserMultiplier(int $userId, string $taskDate): void
  709. {
  710. $row = DB::connection('write')->table(TableName::agent() . 'superball_user_multiplier')
  711. ->where('user_id', $userId)
  712. ->lockForUpdate()
  713. ->first();
  714. $multiplier = self::MULTIPLIER_MIN;
  715. $consecutive = 1;
  716. if ($row) {
  717. $last = $row->last_task_date ? (string) $row->last_task_date : null;
  718. $prev = Carbon::parse($taskDate)->subDay()->format('Y-m-d');
  719. if ($last === $prev) {
  720. $consecutive = (int) $row->consecutive_days + 1;
  721. $multiplier = min(self::MULTIPLIER_MAX, (float) $row->multiplier + self::MULTIPLIER_STEP);
  722. } elseif ($last !== null && $last !== $taskDate) {
  723. $daysDiff = (int) Carbon::parse($taskDate)->diffInDays(Carbon::parse($last));
  724. if ($daysDiff > 1) {
  725. $multiplier = max(self::MULTIPLIER_MIN, (float) $row->multiplier - self::MULTIPLIER_STEP);
  726. $consecutive = 1;
  727. } else {
  728. $multiplier = (float) $row->multiplier;
  729. $consecutive = (int) $row->consecutive_days + 1;
  730. }
  731. }
  732. }
  733. DB::connection('write')->table(TableName::agent() . 'superball_user_multiplier')->updateOrInsert(
  734. ['user_id' => $userId],
  735. [
  736. 'consecutive_days' => $consecutive,
  737. 'last_task_date' => $taskDate,
  738. 'multiplier' => $multiplier,
  739. 'updated_at' => now()->format('Y-m-d H:i:s'),
  740. ]
  741. );
  742. }
  743. }