BalanceLogService.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. <?php
  2. namespace App\Services;
  3. use App\Models\ActivityReward;
  4. use App\Models\BalanceLog;
  5. use App\Models\User;
  6. use App\Models\Config;
  7. use App\Models\WalletBonus;
  8. use App\Models\Wallet;
  9. use App\Models\Level;
  10. use App\Models\RechargeChannelGroup;
  11. use App\Models\UserLogin;
  12. // 余额额变动记录
  13. class BalanceLogService extends BaseService
  14. {
  15. public static string $MODEL = BalanceLog::class;
  16. //后台充值可选择的类型
  17. public static array $manualRecharge = ['人工充值', '注册赠送', '优惠活动'];
  18. //需要计算回水的类型
  19. public static array $computeBackFlowChangeTypes = ['充值', '人工充值', '三方充值', '提现', '人工扣款', '三方提现'];
  20. //全部类型
  21. public static array $RW = [
  22. '充值', '人工充值', '三方充值', '注册赠送', '优惠活动',
  23. '提现', '人工扣款', '三方提现',
  24. '体彩投注','体彩退款','体彩和局退款','体彩中奖','体彩输半退款',
  25. '新澳门六合彩投注','新澳门六合彩退款','新澳门六合彩和局退款','新澳门六合彩中奖',
  26. '香港六合彩投注','香港六合彩退款','香港六合彩和局退款','香港六合彩中奖','加拿大28投注','极速28投注',
  27. '澳门六合彩投注','澳门六合彩退款','澳门六合彩和局退款','澳门六合彩中奖',
  28. '急速六合彩投注','急速六合彩退款','急速六合彩和局退款','急速六合彩中奖',
  29. '极速赛车投注','极速赛车退款','极速赛车和局退款','极速赛车中奖',
  30. '极速时时彩投注','极速时时彩退款','极速时时彩和局退款','极速时时彩中奖',
  31. '极速飞艇投注','极速飞艇退款','极速飞艇和局退款','极速飞艇中奖',
  32. '极速快3投注','极速快3退款','极速快3和局退款','极速快3中奖',
  33. 'SG时时彩投注','SG时时彩退款','SG时时彩和局退款','SG时时彩中奖',
  34. 'SG飞艇投注','SG飞艇退款','SG飞艇和局退款','SG飞艇中奖',
  35. 'SG快3投注','SG快3退款','SG快3和局退款','SG快3中奖',
  36. '投注','中奖', '资产转移', '比比返', '返水', '回水', '笔笔返', '投注退分','充值返现','即充即送','老用户回归','余额宝转入','转出至余额宝','余额宝利息','流水解冻'
  37. ];
  38. public static function init($telegram, $data, $chatId, $firstName, $messageId, $callbackId): void
  39. {
  40. switch ($data) {
  41. case"todayFlowAlert":// 今日流水弹窗
  42. $alertText = BalanceLogService::getTodayFlowing($chatId)['text'];
  43. BalanceLogService::alertNotice($callbackId, $alertText);
  44. break;
  45. default:
  46. //流水列表,下一页
  47. $pattern = "/^FlowingHistoryPage@@\d+$/";
  48. if (preg_match($pattern, $data)) {
  49. $page = preg_replace('/^FlowingHistoryPage@@/', '', $data);
  50. $page = intval($page);
  51. $returnMsg = BalanceLogService::getFlowingHistory($chatId, $messageId, $page);
  52. $telegram->editMessageText($returnMsg);
  53. }
  54. break;
  55. }
  56. }
  57. /**
  58. * @description: 获取查询条件
  59. * @param {array} $search 查询内容
  60. * @return {array}
  61. */
  62. public static function getWhere(array $search = []): array
  63. {
  64. $where = [];
  65. if (isset($search['coin']) && !empty($search['coin'])) {
  66. $where[] = ['balance_logs.coin', '=', $search['coin']];
  67. }
  68. if (isset($search['net']) && !empty($search['net'])) {
  69. $where[] = ['balance_logs.net', '=', $search['net']];
  70. }
  71. if (isset($search['address']) && !empty($search['address'])) {
  72. $where[] = ['balance_logs.address', '=', $search['address']];
  73. }
  74. if (isset($search['id']) && !empty($search['id'])) {
  75. $where[] = ['balance_logs.id', '=', $search['id']];
  76. }
  77. if (isset($search['member_id']) && !empty($search['member_id'])) {
  78. $where[] = ['balance_logs.member_id', '=', $search['member_id']];
  79. }
  80. if (isset($search['type']) && !empty($search['type'])) {
  81. $where[] = ['balance_logs.type', '=', $search['type']];
  82. }
  83. if (isset($search['change_type']) && !empty($search['change_type'])) {
  84. $where[] = ['balance_logs.change_type', '=', $search['change_type']];
  85. }
  86. if (isset($search['start_time']) && !empty($search['start_time'])) {
  87. $where[] = ['balance_logs.created_at', '>=', "{$search['start_time']} 00:00:00"];
  88. $where[] = ['balance_logs.created_at', '<=', "{$search['end_time']} 23:59:59"];
  89. }
  90. if (isset($search['first_name']) && !empty($search['first_name'])) {
  91. $where[] = ['users.first_name', 'like', "%" . $search['first_name'] . "%"];
  92. }
  93. return $where;
  94. }
  95. /**
  96. * @description: 查询单条数据
  97. * @param array $search
  98. * @return \App\Models\Coin|null
  99. */
  100. public static function findOne(array $search): ?BalanceLog
  101. {
  102. return static::model()::where(static::getWhere($search))->first();
  103. }
  104. /**
  105. * @description: 查询所有数据
  106. * @param array $search
  107. * @return \Illuminate\Database\Eloquent\Collection
  108. */
  109. public static function findAll(array $search = [])
  110. {
  111. return static::model()::where(static::getWhere($search))->get();
  112. }
  113. /**
  114. * @description: 分页查询
  115. * @param array $search
  116. * @return array
  117. */
  118. public static function paginate(array $search = []): array
  119. {
  120. $limit = isset($search['limit']) ? $search['limit'] : 15;
  121. $paginator = static::model()::where(static::getWhere($search))
  122. ->when(isset($search['change_types']) && !empty($search['change_types']), function ($query) use ($search) {
  123. return $query->whereIn('change_type', $search['change_types']);
  124. })
  125. ->orderBy('updated_at', 'desc')
  126. ->paginate($limit);
  127. return ['total' => $paginator->total(), 'data' => $paginator->items()];
  128. }
  129. /**
  130. * @description: 生成资金变动日志
  131. * @param {*} $memberId
  132. * @param {*} $amount
  133. * @param {*} $before_balance
  134. * @param {*} $after_balance
  135. * @param {*} $change_type
  136. * @param {*} $related_id
  137. * @param {*} $remark
  138. * @return {*}
  139. */
  140. public static function addLog($memberId, $amount, $before_balance, $after_balance, $change_type, $related_id, $remark, $room_id = null)
  141. {
  142. //回水相关
  143. if (in_array($change_type, static::$computeBackFlowChangeTypes)) {
  144. BackflowService::updateOrCreate((string)$memberId, floatval($amount));
  145. }
  146. $data = [];
  147. $data['member_id'] = $memberId;
  148. $data['amount'] = $amount;
  149. $data['before_balance'] = $before_balance;
  150. $data['after_balance'] = $after_balance;
  151. $data['change_type'] = $change_type;
  152. $data['related_id'] = $related_id;
  153. $data['remark'] = $remark;
  154. if ($room_id) $data['room_id'] = $room_id;
  155. $result = static::$MODEL::create($data);
  156. //充值返现活动
  157. if ( in_array($change_type, ['充值','人工充值','三方充值'])) {
  158. $user = User::where('member_id', $memberId)->first();
  159. if ($user->from == 1) {
  160. //充值更新用户等级
  161. $total_recharge = self::getTotalRecharge($memberId);
  162. $total_recharge = bcadd($total_recharge, $amount, 2);
  163. $level = self::calculateLevel($total_recharge);
  164. if ($level > $user->level) {
  165. $user->level = $level;
  166. $user->save();
  167. }
  168. $remark_amount = bcadd($amount, 0, 2);
  169. //返现比例(给邀请人返现)
  170. $rate = Config::where('field', 'recharge_rate')->first()->val ?? 0;
  171. $add_amount = bcmul($amount, $rate/100, 2);
  172. if ($add_amount > 0) {
  173. //被邀请人每次充值,都给邀请人返现,直接可用余额
  174. $agent_user_code = $user->agent_user_code;
  175. if (!empty($agent_user_code)) {
  176. $agent_member_id = User::where('user_code', $agent_user_code)->value('member_id');
  177. if (!empty($agent_member_id)) {
  178. $balanceData = WalletService::updateBalance($agent_member_id, $add_amount);
  179. BalanceLogService::addLog($agent_member_id, $add_amount, $balanceData['before_balance'], $balanceData['after_balance'], '充值返现', $related_id, '被邀请人:'.$memberId."充值金额为:{$remark_amount}");
  180. }
  181. }
  182. }
  183. //用户活动
  184. $activity_type = RechargeChannelGroup::getActivityType($user->recharge_channel_group_id);
  185. if ($activity_type) {
  186. $walletInfo = Wallet::where('member_id', $memberId)->first();
  187. if (in_array('recharge', $activity_type)) {
  188. //即充即送-返彩活动
  189. $bonusAmount = self::calculateRechargeBonus($amount,$memberId, $related_id);
  190. if ($bonusAmount > 0) {
  191. static::$MODEL::create([
  192. 'type' => 2,
  193. 'member_id' => $memberId,
  194. 'amount' => $bonusAmount,
  195. 'before_balance' => $walletInfo->frozen_balance,
  196. 'after_balance' => bcadd($walletInfo->frozen_balance, $bonusAmount, 2),
  197. 'change_type' => '即充即送',
  198. 'frozen_status' => 1,
  199. 'related_id' => $related_id,
  200. 'remark' => '充值金额为:'.$remark_amount,
  201. ]);
  202. $walletInfo->frozen_balance = bcadd($walletInfo->frozen_balance, $bonusAmount, 2);
  203. }
  204. }
  205. if (in_array('old_user', $activity_type)) {
  206. //老用户回归-返彩活动
  207. $bonusAmount = self::calculateUserReturnRechargeBonus($amount,$memberId, $level, $related_id);
  208. if ($bonusAmount > 0) {
  209. static::$MODEL::create([
  210. 'type' => 2,
  211. 'member_id' => $memberId,
  212. 'amount' => $bonusAmount,
  213. 'before_balance' => $walletInfo->frozen_balance,
  214. 'after_balance' => bcadd($walletInfo->frozen_balance, $bonusAmount, 2),
  215. 'change_type' => '老用户回归',
  216. 'frozen_status' => 1,
  217. 'related_id' => $related_id,
  218. 'remark' => '充值金额为:'.$remark_amount,
  219. ]);
  220. $walletInfo->frozen_balance = bcadd($walletInfo->frozen_balance, $bonusAmount, 2);
  221. }
  222. }
  223. $walletInfo->save();
  224. }
  225. }
  226. }
  227. return $result;
  228. }
  229. /**
  230. * 获取用户累计充值金额
  231. */
  232. public static function getTotalRecharge($memberId): float
  233. {
  234. return static::$MODEL::where('member_id', $memberId)->where('type',1)->whereIn('change_type', ['充值','人工充值', '三方充值'])->sum('amount');
  235. }
  236. /**
  237. * 根据历史累计充值金额计算等级
  238. * @param float $totalAmount 历史累计充值金额
  239. * @return int 等级(1-5)
  240. */
  241. public static function calculateLevel(float $totalAmount): int
  242. {
  243. $levelList = Level::orderBy('recharge', 'desc')->get()->toArray();
  244. foreach ($levelList as $item) {
  245. if ($totalAmount >= $item['recharge']) {
  246. return $item['level'];
  247. }
  248. }
  249. return 0;
  250. }
  251. /**
  252. * @description: 获取今日流水
  253. * @param int $memberId
  254. * @param string|null $date
  255. * @return {*}
  256. */
  257. public static function getTodayFlowing($memberId, $date = null)
  258. {
  259. if (!$date) {
  260. $date = date('Y-m-d');
  261. }
  262. $startTime = date('Y-m-d H:i:s', strtotime($date . ' 00:00:00'));
  263. $endTime = date('Y-m-d H:i:s', strtotime($date . ' 23:59:59'));
  264. $flow = static::model()::where('member_id', $memberId)
  265. ->whereBetween('created_at', [$startTime, $endTime])
  266. ->where('change_type', '投注')
  267. ->sum('amount');
  268. $refund = static::model()::where('member_id', $memberId)
  269. ->whereBetween('created_at', [$startTime, $endTime])
  270. ->where('change_type', '返水')
  271. ->sum('amount');
  272. $profit = static::model()::where('member_id', $memberId)
  273. ->whereBetween('created_at', [$startTime, $endTime])
  274. ->where('change_type', '中奖') //嬴正数 输负数
  275. ->sum('amount');
  276. $walletInfo = WalletService::model()::where('member_id', $memberId)->first();
  277. $text = '';
  278. $text .= "当日流水: " . number_format((0 - $flow), 2) . "\n";
  279. $text .= "返水额度: " . number_format($refund, 2) . "\n";
  280. $text .= "当日盈亏: " . number_format(($profit + $refund + $flow), 2) . "\n";
  281. $text .= "余额: " . number_format($walletInfo['available_balance'], 2) . "\n";
  282. return [
  283. 'chat_id' => $memberId,
  284. 'text' => $text
  285. ];
  286. }
  287. public static function getFlowingHistory($memberId, $messageId = null, $page = 1, $limit = 5)
  288. {
  289. $dateTime = date('Y-m-d 00:00:00');
  290. $list = [];
  291. for ($i = 0; $i < $limit; $i++) {
  292. $newIndex = ($page - 1) * $limit + $i;
  293. $date = date('Y-m-d', strtotime($dateTime . " -{$newIndex} day"));
  294. $startTime = date('Y-m-d H:i:s', strtotime($date . ' 00:00:00'));
  295. $endTime = date('Y-m-d H:i:s', strtotime($date . ' 23:59:59'));
  296. $flow = static::model()::where('member_id', $memberId)
  297. ->whereBetween('created_at', [$startTime, $endTime])
  298. ->where('change_type', '投注')
  299. ->sum('amount');
  300. $refund = static::model()::where('member_id', $memberId)
  301. ->whereBetween('created_at', [$startTime, $endTime])
  302. ->where('change_type', '返水')
  303. ->sum('amount');
  304. $profit = static::model()::where('member_id', $memberId)
  305. ->whereBetween('created_at', [$startTime, $endTime])
  306. ->where('change_type', '中奖') //嬴正数 输负数
  307. ->sum('amount');
  308. $list[] = [
  309. 'date' => $date,
  310. 'flow' => number_format($flow, 2),
  311. 'refund' => number_format($refund, 2),
  312. 'profit' => number_format(($profit + $refund + $flow), 2)
  313. ];
  314. }
  315. // $startTime = date('Y-m-d H:i:s',strtotime($date . ' 00:00:00'));
  316. // $endTime = date('Y-m-d H:i:s',strtotime($date . ' 23:59:59'));
  317. // $list = static::model()::where('member_id', $memberId)
  318. // ->whereBetween('created_at', [$startTime, $endTime])
  319. // ->orderBy('created_at', 'desc')
  320. // ->get();
  321. $text = lang("流水历史") . " \n";
  322. foreach ($list as $item) {
  323. $text .= "---------------------\n";
  324. $text .= lang("日期") . ": {$item['date']} \n";
  325. $text .= lang("流水") . ": {$item['flow']} \n";
  326. $text .= lang("返水") . ": {$item['refund']} \n";
  327. $text .= lang("盈利") . ": {$item['profit']} \n";
  328. }
  329. $keyboard = [[
  330. ['text' => "👇" . lang("下一页"), 'callback_data' => "FlowingHistoryPage@@" . ($page + 1)]
  331. ]];
  332. if ($page > 1) {
  333. array_unshift($keyboard[0], ['text' => "👆" . lang("上一页"), 'callback_data' => "FlowingHistoryPage@@" . ($page - 1)]);
  334. }
  335. return [
  336. 'chat_id' => $memberId,
  337. 'text' => $text,
  338. 'message_id' => $messageId,
  339. 'reply_markup' => json_encode(['inline_keyboard' => $keyboard]),
  340. ];
  341. }
  342. /**
  343. * 计算充值的返现金额
  344. * @param float $amount 充值金额(人民币)
  345. */
  346. public static function calculateRechargeBonus($amount,$memberId, $related_id = null)
  347. {
  348. $activity = ActivityReward::where('lang','zh')->where('type',3)->where('status',1)->where('start_time', '<', time())->where('end_time', '>', time())->first();
  349. if (!$activity) {
  350. return false;
  351. }
  352. $params = $activity->params ? json_decode($activity->params, true) : [];
  353. if (!$params || empty($params['reward_ratio'])) {
  354. return false;
  355. }
  356. // 规则1:单笔最低金额
  357. if (isset($params['min_recharge_amount']) && $amount < $params['min_recharge_amount']) {
  358. return false;
  359. }
  360. // 规则2:必须是每日前几笔充值
  361. if (!empty($params['reward_limit_count'])) {
  362. //今日已充值数
  363. $dailyOrder = static::model()::where('member_id', $memberId)
  364. ->whereBetween('created_at', [date('Y-m-d 00:00:00'), date('Y-m-d 23:59:59')])
  365. ->whereIn('change_type', ['充值','三方充值'])
  366. ->count();
  367. if ($dailyOrder > $params['reward_limit_count']) {
  368. return false;
  369. }
  370. }
  371. // 规则3:返彩比例,不超过单笔最高10000元
  372. $rate = bcdiv($params['reward_ratio'], 100, 6); // 0.5%
  373. $maxBonus = $params['max_reward_amount'] ?? 10000; // 单笔最高上限
  374. $calculatedBonus = bcmul($amount, $rate, 2); // 保留两位小数
  375. $bonusAmount = min($calculatedBonus, $maxBonus);
  376. //倍率流水
  377. $need_flow = !empty($params['reward_turnover_ratio']) ? bcmul($bonusAmount, $params['reward_turnover_ratio'], 2) : $bonusAmount;
  378. //返彩流水
  379. WalletBonus::addData($memberId, 1, $bonusAmount, $activity->id, $related_id, $need_flow);
  380. return $bonusAmount;
  381. }
  382. /**
  383. * 计算老用户回归当日的充值返现金额
  384. * @param float $amount 充值金额(人民币)
  385. */
  386. public static function calculateUserReturnRechargeBonus($amount,$memberId, $level, $related_id = null)
  387. {
  388. $activity = ActivityReward::where('lang','zh')->where('type',4)->where('status',1)->where('start_time', '<', time())->where('end_time', '>', time())->first();
  389. if (!$activity) {
  390. return false;
  391. }
  392. $params = $activity->params ? json_decode($activity->params, true) : [];
  393. if (!$params || empty($params['no_login_days']) || empty($params['reward_rules'])) {
  394. return false;
  395. }
  396. // 规则1:单笔最低金额
  397. if (isset($params['min_amount']) && $amount < $params['min_amount']) {
  398. return false;
  399. }
  400. // 规则2:多少天未登录
  401. $noLoginDays = UserLogin::getNotLoginDays($memberId);
  402. if ($noLoginDays < $params['no_login_days']) {
  403. return false;
  404. }
  405. foreach($params['reward_rules'] as $rule) {
  406. if (isset($rule['start_level']) && isset($rule['end_level'])) {
  407. if ($level >= $rule['start_level'] && $level <= $rule['end_level']) {
  408. $bonusAmount = $rule['bonus'];
  409. //倍率流水
  410. $need_flow = !empty($rule['turnover_rate']) ? bcmul($bonusAmount, $rule['turnover_rate'], 2) : $bonusAmount;
  411. break;
  412. }
  413. }
  414. }
  415. if (!isset($bonusAmount)) {
  416. return false;
  417. }
  418. //返彩流水
  419. WalletBonus::addData($memberId, 3, $bonusAmount, $activity->id, $related_id, $need_flow);
  420. return $bonusAmount;
  421. }
  422. }