BalanceLogService.php 17 KB

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