SuperballActivityService.php 34 KB

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