BalanceLogService.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | LARAVEL8.0 框架 [ LARAVEL ][ RXThinkCMF ]
  4. // +----------------------------------------------------------------------
  5. // | 版权所有 2017~2021 LARAVEL研发中心
  6. // +----------------------------------------------------------------------
  7. // | 官方网站: http://www.laravel.cn
  8. // +----------------------------------------------------------------------
  9. // | Author: laravel开发员 <laravel.qq.com>
  10. // +----------------------------------------------------------------------
  11. namespace App\Services\Common;
  12. use App\Models\AccountLogModel;
  13. use App\Models\ActionLogModel;
  14. use App\Models\BalanceLogModel;
  15. use App\Models\MemberModel;
  16. use App\Services\Api\FinanceService;
  17. use App\Services\BaseService;
  18. use App\Services\CregisPayService;
  19. use App\Services\RedisService;
  20. use App\Services\WalletService;
  21. use Illuminate\Support\Facades\DB;
  22. /**
  23. * 充值提现管理-服务类
  24. * @author laravel开发员
  25. * @since 2020/11/11
  26. * @package App\Services\Common
  27. */
  28. class BalanceLogService extends BaseService
  29. {
  30. // 静态对象
  31. protected static $instance = null;
  32. /**
  33. * 构造函数
  34. * @author laravel开发员
  35. * @since 2020/11/11
  36. */
  37. public function __construct()
  38. {
  39. $this->model = new BalanceLogModel();
  40. }
  41. /**
  42. * 静态入口
  43. * @return static|null
  44. */
  45. public static function make()
  46. {
  47. if (!self::$instance) {
  48. self::$instance = (new static());
  49. }
  50. return self::$instance;
  51. }
  52. /**
  53. * 获取列表
  54. * @param $params 参数
  55. * @param int $pageSize 分页大小:默认 15
  56. * @return array
  57. */
  58. public function getDataList($params, $pageSize = 10, $field = [])
  59. {
  60. $query = $this->getQuery($params);
  61. $list = $query->select($field ? $field : ['a.*', 'b.nickname'])
  62. ->orderBy('a.status','asc')
  63. ->orderBy('a.create_time','desc')
  64. ->orderBy('a.pay_at','desc')
  65. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  66. $list = $list ? $list->toArray() : [];
  67. if ($list) {
  68. foreach ($list['data'] as &$item) {
  69. $item['create_time'] = datetime($item['create_time'],'Y-m-d H:i:s');
  70. if($item['user_type'] == 1){
  71. $item['uid'] = $item['user_id'];
  72. $item['account'] = isset($item['nickname'])&& $item['nickname']? $item['nickname'] : $item['user_id'];
  73. }
  74. }
  75. }
  76. return [
  77. 'pageSize' => $pageSize,
  78. 'total' => isset($list['total']) ? $list['total'] : 0,
  79. 'list' => isset($list['data']) ? $list['data'] : []
  80. ];
  81. }
  82. /**
  83. * 查询构造
  84. * @param $params
  85. * @return \Illuminate\Database\Eloquent\Builder
  86. */
  87. public function getQuery($params)
  88. {
  89. $where = ['a.mark' => 1];
  90. return $this->model->with(['member'])
  91. ->from('balance_logs as a')
  92. ->leftJoin('member as b', function($join) {
  93. $join->on('b.id','=', 'a.user_id')->where('a.user_type',1);
  94. })
  95. ->where($where)
  96. ->where(function ($query) use ($params) {
  97. $kw = isset($params['keyword']) ? trim($params['keyword']) : '';
  98. if ($kw) {
  99. $query->where('b.id', '=', $params['keyword'])
  100. ->orWhere('b.nickname', 'like', "%{$params['keyword']}%");
  101. }
  102. })
  103. ->where(function ($query) use($params){
  104. // 日期
  105. $date = isset($params['date']) ? $params['date'] : [];
  106. $start = isset($date[0])? $date[0] : '';
  107. $end = isset($date[1])? $date[1] : '';
  108. $end = $start>=$end? '' : $end;
  109. if ($start) {
  110. $query->where('a.create_time','>=', strtotime($start));
  111. }
  112. if($end){
  113. $query->where('a.create_time','<=', strtotime($end));
  114. }
  115. $orderNo = isset($params['order_no'])? trim($params['order_no']) : '';
  116. if($orderNo){
  117. $query->where('a.order_no', 'like', "%{$orderNo}%");
  118. }
  119. $walletUrl = isset($params['wallet_url'])? trim($params['wallet_url']) : '';
  120. if($walletUrl){
  121. $query->where('a.wallet_url', '=', $walletUrl);
  122. }
  123. $ptWalletUrl = isset($params['pt_wallet_url'])? trim($params['pt_wallet_url']) : '';
  124. if($ptWalletUrl){
  125. $query->where('a.pt_wallet_url', '=', $ptWalletUrl);
  126. }
  127. $hash = isset($params['hash'])? trim($params['hash']) : '';
  128. if($hash){
  129. $query->where('a.hash', '=', $hash);
  130. }
  131. $userType = isset($params['user_type'])? $params['user_type'] : 0;
  132. if ($userType) {
  133. $query->where('a.user_type', $userType);
  134. }
  135. $payType = isset($params['pay_type'])? $params['pay_type'] : 0;
  136. if ($payType) {
  137. $query->where('a.pay_type', $payType);
  138. }
  139. $payStatus = isset($params['pay_status'])? $params['pay_status'] : 0;
  140. if ($payStatus) {
  141. $query->where('a.pay_status', $payStatus);
  142. }
  143. $type = isset($params['type'])? $params['type'] : 0;
  144. if (is_array($type)) {
  145. $query->whereIn('a.type', $type);
  146. } else if($type){
  147. $query->where('a.type', $type);
  148. }
  149. $coinType = isset($params['coin_type'])? $params['coin_type'] : 0;
  150. if (is_array($coinType)) {
  151. $query->whereIn('a.coin_type', $coinType);
  152. } else if($coinType){
  153. $query->where('a.coin_type', $coinType);
  154. }
  155. $status = isset($params['status'])? $params['status'] : 0;
  156. if (is_array($status)) {
  157. $query->whereIn('a.status', $status);
  158. } else if($status){
  159. $query->where('a.status', $status);
  160. }
  161. });
  162. }
  163. /**
  164. * 统计
  165. * @param $params
  166. * @return array
  167. */
  168. public function count($params)
  169. {
  170. $query = $this->getQuery($params);
  171. $count = $query->count('a.id');
  172. $total = $query->sum('a.money');
  173. return [
  174. 'count' => $count,
  175. 'total' => $total
  176. ];
  177. }
  178. /**
  179. * 充值订单数量检测
  180. * @return array|false|mixed
  181. */
  182. public function checkCount()
  183. {
  184. $cacheKey = "caches:withdraw:checkCount";
  185. $data = RedisService::get($cacheKey);
  186. if($data || RedisService::exists($cacheKey)){
  187. return $data;
  188. }
  189. $data = $this->model->where(['type'=>2,'status'=>1,'mark'=>1])->count('id');
  190. if($data>=0){
  191. RedisService::set($cacheKey, $data, rand(3,5));
  192. }
  193. return $data;
  194. }
  195. /**
  196. * 统计累计质押金额
  197. * @param $userId 用户ID
  198. * @return array|false|mixed
  199. */
  200. public function getTotalByUser($userId, $type = 1)
  201. {
  202. $cacheKey = "caches:balanceLog:total_{$userId}_{$type}";
  203. $data = RedisService::get($cacheKey);
  204. if($data || RedisService::exists($cacheKey)){
  205. return $data?$data:'0.00';
  206. }
  207. // 真实充提
  208. $data = $this->model->where(['user_id'=>$userId,'type'=>$type,'mark'=>1])->whereIn('status',[1,2])->sum('money');
  209. // 上下分
  210. $total = AccountLogModel::where(['user_id'=> $userId,'type'=>$type==1?5:6,'status'=>1,'mark'=>1])->sum('money');
  211. $data = round($total + $data, 2);
  212. RedisService::set($cacheKey, $data, rand(5,10));
  213. return $data?$data:'0.00';
  214. }
  215. /**
  216. * 团队真实/上下分充提数据
  217. * @param $userId 用户ID
  218. * @param int $type
  219. * @return array|int[]|mixed
  220. */
  221. public function getTeamTotalByUser($userId, $type=1)
  222. {
  223. $cacheKey = "caches:balanceLog:teamTotal_{$userId}_{$type}";
  224. $data = RedisService::get($cacheKey);
  225. if($data || RedisService::exists($cacheKey)){
  226. return $data?$data:['recharge'=>0,'withdraw'=>0,'difference'=>0];
  227. }
  228. // 真实充提
  229. if($type == 1){
  230. $recharge = $this->model->from('balance_logs as a')
  231. ->leftJoin('member as b','a.user_id','b.id')
  232. ->where(function($query) use($userId){
  233. $query->whereRaw("FIND_IN_SET({$userId},lev_b.parent_ids)")->orWhere('a.user_id', $userId);
  234. })
  235. ->where(['a.type'=>1,'a.mark'=>1,'b.mark'=>1])
  236. ->whereIn('a.status',[1,2])
  237. ->sum('a.money');
  238. $withdraw = $this->model->from('balance_logs as a')
  239. ->leftJoin('member as b','a.user_id','b.id')
  240. ->where(function($query) use($userId){
  241. $query->whereRaw("FIND_IN_SET({$userId},lev_b.parent_ids)")->orWhere('a.user_id', $userId);
  242. })
  243. ->where(['a.type'=>2,'a.mark'=>1,'b.mark'=>1])
  244. ->whereIn('a.status',[1,2])
  245. ->sum('a.money');
  246. $withdraw = abs($withdraw);
  247. }else{
  248. // 上下分
  249. $recharge = AccountLogModel::from('account_log as a')
  250. ->leftJoin('member as b','a.user_id','b.id')
  251. ->where(function($query) use($userId){
  252. $query->whereRaw("FIND_IN_SET({$userId},lev_b.parent_ids)")->orWhere('a.user_id', $userId);
  253. })
  254. ->where(['a.type'=>5,'a.status'=>1,'a.mark'=>1,'b.mark'=>1])
  255. ->sum('a.money');
  256. $withdraw = AccountLogModel::from('account_log as a')
  257. ->leftJoin('member as b','a.user_id','b.id')
  258. ->where(function($query) use($userId){
  259. $query->whereRaw("FIND_IN_SET({$userId},lev_b.parent_ids)")->orWhere('a.user_id', $userId);
  260. })
  261. ->where(['a.type'=>6,'a.status'=>1,'a.mark'=>1,'b.mark'=>1])
  262. ->sum('a.money');
  263. $withdraw = abs($withdraw);
  264. }
  265. $data = ['recharge'=>$recharge,'withdraw'=>$withdraw,'difference'=>round($recharge - $withdraw, 2)];
  266. RedisService::set($cacheKey, $data, rand(5,10));
  267. return $data;
  268. }
  269. /**
  270. * 提现审核
  271. * @param $params
  272. * @return bool
  273. */
  274. public function withdrawAuth($params)
  275. {
  276. $id = isset($params['id'])? $params['id'] : 0;
  277. $checkStatus = isset($params['status'])? $params['status'] : 0;
  278. $remark = isset($params['audit_remark'])? trim($params['audit_remark']) : '';
  279. $payMoney = isset($params['actual_money'])? floatval($params['actual_money']) : 0;
  280. if(!in_array($checkStatus,[2,3])){
  281. $this->error = 1073;
  282. return false;
  283. }
  284. $info = $this->model->with(['member'])->where(['id'=> $id,'mark'=>1])->first();
  285. $type = isset($info['type'])? $info['type'] : 0;
  286. $coinType = isset($info['coin_type'])? $info['coin_type'] : 0;
  287. $accountUserId = isset($info['user_id'])? $info['user_id'] : 0;
  288. $money = isset($info['money'])? $info['money'] : 0;
  289. $actualMoney = isset($info['actual_money'])? $info['actual_money'] : 0;
  290. $fee = isset($info['fee'])? $info['fee'] : 0;
  291. $status = isset($info['status'])? $info['status'] : 0;
  292. $accountWalletUrl = isset($info['wallet_url'])? $info['wallet_url'] : '';
  293. $orderNo = isset($info['order_no'])? $info['order_no'] : '';
  294. if($id<=0 || empty($info) || $accountUserId<=0 || empty($orderNo) || empty($accountWalletUrl)){
  295. $this->error = 4001;
  296. return false;
  297. }
  298. if($actualMoney<=0 && $payMoney<=0){
  299. $this->error = 4010;
  300. return false;
  301. }
  302. $payMoney = $payMoney? $payMoney : $actualMoney;
  303. if($payMoney > $money){
  304. $this->error = 4011;
  305. return false;
  306. }
  307. if($status != 1){
  308. $this->error = 4002;
  309. return false;
  310. }
  311. if($type != 2){
  312. $this->error = 4008;
  313. return false;
  314. }
  315. $cacheKey ="caches:withdraw:lock_{$id}";
  316. if(RedisService::get($cacheKey)){
  317. $this->error = 1034;
  318. return false;
  319. }
  320. // 绑定的用户ID
  321. $userId = $accountUserId;
  322. $userInfo = isset($info['member'])? $info['member'] : [];
  323. if(empty($userInfo)){
  324. $this->error = 4004;
  325. return false;
  326. }
  327. // 审核处理
  328. RedisService::set($cacheKey, true, rand(5, 10));
  329. DB::beginTransaction();
  330. // 审核通过到账处理
  331. $coinName = $coinType==1?'USDT余额':'收益';
  332. if($checkStatus == 2) {
  333. // USDT链上打款
  334. $walletUrl = isset($info['wallet_url'])? $info['wallet_url'] : '';
  335. if(empty($walletUrl)){
  336. DB::rollBack();
  337. $this->error = 4005;
  338. RedisService::clear($cacheKey);
  339. return false;
  340. }
  341. // 用户钱包和提现地址验证
  342. $walletToken = isset($userInfo['wallet_token'])? $userInfo['wallet_token'] : '';
  343. if($walletUrl!=$accountWalletUrl || $walletToken != make_wallet_token($walletUrl, $userId)){
  344. DB::rollBack();
  345. $this->error = 4009;
  346. RedisService::clear($cacheKey);
  347. return false;
  348. }
  349. // 验证是否为有效Sol链地址
  350. // if (!WalletService::make()->checkAddress($walletUrl)) {
  351. // DB::rollBack();
  352. // $this->error = CregisPayService::make()->getError();
  353. // RedisService::clear($cacheKey);
  354. // return false;
  355. // }
  356. $updateData = ['status'=>2,'actual_money'=>$payMoney,'audit_remark'=>$remark, 'update_time' => time()];
  357. if(!$this->model->where(['id'=> $id])->update($updateData)){
  358. DB::rollBack();
  359. $this->error = 4006;
  360. RedisService::clear($cacheKey);
  361. return false;
  362. }
  363. // U盾出账
  364. try {
  365. $payRemark = $coinType == 1 ? 'USDT余额提现' : '佣金收益提现';
  366. $count = 0;
  367. while($count < 3){
  368. $result = CregisPayService::make()->withdraw($walletUrl, $payMoney, $orderNo, '1000', '', $payRemark);
  369. if($result){
  370. $count++;
  371. sleep(1);
  372. }else {
  373. break;
  374. }
  375. }
  376. // 平台钱包出账
  377. $data = isset($result['data'])? $result['data'] : [];
  378. $tradeCid = isset($data['cid']) ? $data['cid'] : '';
  379. if(empty($tradeCid)){
  380. DB::rollBack();
  381. $this->error = CregisPayService::make()->getError();
  382. RedisService::clear($cacheKey);
  383. return false;
  384. }
  385. $updateData = ['trade_cid' => $tradeCid, 'update_time' => time()];
  386. if(!$this->model->where(['id'=> $id])->update($updateData)){
  387. DB::rollBack();
  388. $this->error = 4006;
  389. RedisService::clear($cacheKey);
  390. return false;
  391. }
  392. } catch (\Exception $exception){
  393. DB::rollBack();
  394. $this->error = $exception->getMessage();
  395. RedisService::clear($cacheKey);
  396. return false;
  397. }
  398. }
  399. // 审核失败驳回退款
  400. else{
  401. $updateData = ['status'=> 3,'audit_remark'=> $remark,'update_time'=> time()];
  402. if(!$this->model->where(['id'=> $id])->update($updateData)){
  403. DB::rollBack();
  404. $this->error = 1072;
  405. RedisService::clear($cacheKey);
  406. return false;
  407. }
  408. // 会员:USDT驳回入账
  409. if($coinType == 1){
  410. $balance = isset($userInfo['usdt'])? $userInfo['usdt'] : 0;
  411. $updateData = [
  412. 'usdt' => DB::raw("usdt + {$money}"),
  413. 'sbt' => DB::raw("sbt + {$fee}"),
  414. 'update_time'=>time()
  415. ];
  416. if (!MemberModel::where(['id' => $accountUserId])->update($updateData)){
  417. DB::rollBack();
  418. $this->error = 1072;
  419. RedisService::clear($cacheKey);
  420. return false;
  421. }
  422. }
  423. // 收益退回
  424. else if($coinType == 2){
  425. $balance = isset($userInfo['profit'])? $userInfo['profit'] : 0;
  426. $updateData = [
  427. 'profit' => DB::raw("profit + {$money}"),
  428. 'sbt' => DB::raw("sbt + {$fee}"),
  429. 'update_time'=>time()
  430. ];
  431. if (!MemberModel::where(['id' => $accountUserId])->update($updateData)){
  432. DB::rollBack();
  433. $this->error = 1072;
  434. RedisService::clear($cacheKey);
  435. return false;
  436. }
  437. }
  438. // 账户明细
  439. $log = [
  440. 'user_id' => $accountUserId,
  441. 'order_no' => $orderNo,
  442. 'type' => 17,
  443. 'coin_type' => $coinType==2? 3 : 1,
  444. 'user_type'=> 1,
  445. 'money' => $money,
  446. 'before_money' => $balance,
  447. 'create_time' => time(),
  448. 'update_time' => date('Y-m-d H:i:s'),
  449. 'action_ip' => get_client_ip(),
  450. 'remark' => "{$coinName}提现退还",
  451. 'status' => 1,
  452. 'mark' => 1,
  453. ];
  454. if(!AccountLogModel::insertGetId($log)){
  455. DB::rollBack();
  456. $this->error = 2029;
  457. RedisService::clear($cacheKey);
  458. return false;
  459. }
  460. }
  461. DB::commit();
  462. $this->error = 1071;
  463. RedisService::clear($cacheKey);
  464. ActionLogModel::setTitle("{$coinName}提现审核");
  465. ActionLogModel::record();
  466. return true;
  467. }
  468. }