BalanceLogService.php 18 KB

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