BalanceLogService.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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\Api;
  12. use App\Models\AccountLogModel;
  13. use App\Models\ActionLogModel;
  14. use App\Models\BalanceLogModel;
  15. use App\Models\MemberBankModel;
  16. use App\Models\MemberModel;
  17. use App\Services\BaseService;
  18. use App\Services\ConfigService;
  19. use App\Services\RedisService;
  20. use Illuminate\Support\Facades\DB;
  21. /**
  22. * 余额管理-服务类
  23. * @author laravel开发员
  24. * @since 2020/11/11
  25. */
  26. class BalanceLogService extends BaseService
  27. {
  28. public static $instance = null;
  29. /**
  30. * 构造函数
  31. * @author laravel开发员
  32. * @since 2020/11/11
  33. * AccountService constructor.
  34. */
  35. public function __construct()
  36. {
  37. $this->model = new BalanceLogModel();
  38. }
  39. /**
  40. * 静态入口
  41. * @return static|null
  42. */
  43. public static function make()
  44. {
  45. if (!self::$instance) {
  46. self::$instance = (new static());
  47. }
  48. return self::$instance;
  49. }
  50. /**
  51. * @param $params
  52. * @param int $pageSize
  53. * @return array
  54. */
  55. public function getDataList($params, $pageSize = 15)
  56. {
  57. $query = $this->getQuery($params);
  58. $list = $query->select(['a.*'])
  59. ->orderBy('a.status', 'asc')
  60. ->orderBy('a.create_time', 'desc')
  61. ->orderBy('a.id', 'desc')
  62. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  63. $list = $list ? $list->toArray() : [];
  64. if ($list) {
  65. foreach ($list['data'] as &$item) {
  66. $item['create_time'] = $item['create_time'] ? datetime($item['create_time'], 'Y-m-d H:i:s') : '';
  67. $item['time_text'] = $item['create_time'] ? datetime($item['create_time'], 'Y年m月d日') : '';
  68. }
  69. }
  70. return [
  71. 'pageSize' => $pageSize,
  72. 'total' => isset($list['total']) ? $list['total'] : 0,
  73. 'list' => isset($list['data']) ? $list['data'] : []
  74. ];
  75. }
  76. public function getQuery($params)
  77. {
  78. $where = ['a.mark' => 1];
  79. $status = isset($params['status']) ? $params['status'] : 0;
  80. $type = isset($params['type']) ? $params['type'] : 0;
  81. if ($status > 0) {
  82. $where['a.status'] = $status;
  83. }
  84. if ($type > 0) {
  85. $where['a.type'] = $type;
  86. }
  87. return $this->model->with(['member'])->from("balance_logs as a")
  88. ->leftJoin('member as b', 'b.id', '=', 'a.user_id')
  89. ->where($where)
  90. ->where(function ($query) use ($params) {
  91. $keyword = isset($params['keyword']) ? $params['keyword'] : '';
  92. $userId = isset($params['user_id']) ? $params['user_id'] : 0;
  93. if ($userId) {
  94. $query->where('a.user_id', $userId);
  95. }
  96. if ($keyword) {
  97. $query->where(function ($query) use ($keyword) {
  98. $query->where('b.nickname', 'like', "%{$keyword}%")
  99. ->orWhere('b.mobile', 'like', "%{$keyword}%")
  100. ->orWhere('b.realname', 'like', "%{$keyword}%");
  101. });
  102. }
  103. $orderNo = isset($params['order_no']) ? trim($params['order_no']) : '';
  104. if ($orderNo) {
  105. $query->where(function ($query) use ($orderNo) {
  106. $query->where('a.order_no', 'like', "%{$orderNo}%");
  107. });
  108. }
  109. $account = isset($params['account']) ? trim($params['account']) : '';
  110. if ($account) {
  111. $query->where(function ($query) use ($account) {
  112. $query->where('a.account', 'like', "%{$account}%");
  113. });
  114. }
  115. })
  116. ->where(function ($query) use ($params) {
  117. // 日期
  118. $date = isset($params['date']) ? $params['date'] : [];
  119. $start = isset($date[0]) ? $date[0] : '';
  120. $end = isset($date[1]) ? $date[1] : '';
  121. $end = $start >= $end ? '' : $end;
  122. if ($start) {
  123. $query->where('a.create_time', '>=', strtotime($start));
  124. }
  125. if ($end) {
  126. $query->where('a.create_time', '<=', strtotime($end));
  127. }
  128. });
  129. }
  130. /**
  131. * 收入提现
  132. * @param $userId
  133. * @param $params
  134. * @return array|false
  135. */
  136. public function withdraw($userId, $params)
  137. {
  138. // 参数验证
  139. $payType = isset($params['pay_type']) && $params['pay_type'] ? intval($params['pay_type']) : 10;
  140. $accountType = isset($params['type']) && $params['type'] ? intval($params['type']) : 1;
  141. $money = isset($params['money']) ? floatval($params['money']) : 0;
  142. $accountId = isset($params['account_id']) ? intval($params['account_id']) : 0;
  143. if ($money <= 0) {
  144. $this->error = '请输入提现金额';
  145. return false;
  146. }
  147. if ($payType != 10 && $accountId <= 0) {
  148. $this->error = '请选择收款账户';
  149. return false;
  150. }
  151. $openWithdraw = ConfigService::make()->getConfigByCode("withdraw_{$accountType}_open", 1);
  152. if (!$openWithdraw) {
  153. $this->error = 2304;
  154. return false;
  155. }
  156. $withdrawMin = ConfigService::make()->getConfigByCode("withdraw_min", 0.1);
  157. if ($withdrawMin > 0 && $money < $withdrawMin) {
  158. $this->error = lang(2305, ['money' => $withdrawMin]);
  159. return false;
  160. }
  161. // 锁
  162. $cacheLockKey = "caches:members:withdraw:{$userId}";
  163. if (RedisService::get($cacheLockKey)) {
  164. $this->error = 1034;
  165. return false;
  166. }
  167. if($accountId){
  168. $accountInfo = MemberBankModel::where(['id' => $accountId, 'user_id' => $userId, 'mark' => 1])->first();
  169. $realname = isset($accountInfo['realname']) ? $accountInfo['realname'] : '';
  170. $account = isset($accountInfo['account']) ? $accountInfo['account'] : '';
  171. $accountName = isset($accountInfo['account_name']) ? $accountInfo['account_name'] : '';
  172. $accountRemark = isset($accountInfo['account_remark']) ? $accountInfo['account_remark'] : '';
  173. if (empty($accountInfo) || empty($realname) || empty($accountName) || empty($account)) {
  174. $this->error = '抱歉,当前收款账户错误请更换后重试';
  175. return false;
  176. }
  177. }else{
  178. $accountName = '微信支付';
  179. $account = '微信零钱';
  180. $accountRemark = '';
  181. }
  182. // 判断用户账号状态
  183. $fields = [1=>'balance',2=>'property',4=>'ls_score'];
  184. $field = isset($fields[$accountType])? $fields[$accountType]:'balance';
  185. RedisService::set($cacheLockKey, ['user_id' => $userId, 'params' => $params], rand(10, 20));
  186. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])->select(['id', 'balance','property','bd_score','ls_score', 'status'])->first();
  187. $realname = isset($userInfo['realname']) ? $userInfo['realname'] : '';
  188. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  189. $balance = isset($userInfo[$field]) ? $userInfo[$field] : 0;
  190. if (empty($userInfo) || $status != 1) {
  191. $this->error = 2016;
  192. RedisService::clear($cacheLockKey);
  193. return false;
  194. }
  195. if ($money > $balance) {
  196. $this->error = '该账户可提现余额不足';
  197. RedisService::clear($cacheLockKey);
  198. return false;
  199. }
  200. // 计算实际到账金额
  201. $poolMoney = 0;
  202. $ptMoney = 0;
  203. $ptRate = 0;
  204. $poolRate = 0;
  205. $total = $money;
  206. $actualMoney = $money;
  207. if($accountType==2){
  208. // 提现金额
  209. $price = PriceService::make()->getTodayPrice(1);
  210. if($price<=0){
  211. $this->error = '请等候今日资产价格刷新后重试~';
  212. RedisService::clear($cacheLockKey);
  213. return false;
  214. }
  215. // 结算比例
  216. $rate = ConfigService::make()->getConfigByCode('withdraw_2_rate',0);
  217. $rate = $rate>0 && $rate<=100? $rate : 100;
  218. $total = moneyFormat($total * $price,2);
  219. $actualMoney = moneyFormat($total * $rate/100, 2);
  220. // 底池比例
  221. $poolRate = ConfigService::make()->getConfigByCode('withdraw_2_back_rate',0);
  222. $poolRate = $poolRate>0 && $poolRate<50? $poolRate : 0;
  223. $poolMoney = round($total * $poolRate/100, 2);
  224. // 运营账户比例
  225. $ptRate = ConfigService::make()->getConfigByCode('withdraw_2_pt_rate',0);
  226. $ptRate = $ptRate>0 && $ptRate<=50? $ptRate : 0;
  227. $ptMoney = round($total * $ptRate/100, 2);
  228. }
  229. // 手续费
  230. $feeRate = ConfigService::make()->getConfigByCode("withdraw_{$accountType}_fee",0);
  231. $feeRate = $feeRate>0 && $feeRate<=50? $feeRate : 0;
  232. $fee = round($actualMoney * $feeRate/100, 2);
  233. $actualMoney = moneyFormat($actualMoney - $fee, 2);
  234. $accountTypeName = ['账户','收益余额','数字资产','报单积分','绿色积分'][$accountType];
  235. $accountTypeName = $accountTypeName?$accountTypeName:'账户';
  236. // 提现处理
  237. DB::beginTransaction();
  238. $updateData = ["{$field}" => DB::raw("{$field} - {$money}"), 'update_time' => time()];
  239. // 会员账户
  240. $userType = 1;
  241. if (!MemberModel::where(['id' => $userId])->update($updateData)) {
  242. DB::rollBack();
  243. $this->error = '提现处理失败';
  244. RedisService::clear($cacheLockKey);
  245. return false;
  246. }
  247. $orderNo = get_order_num('JW');
  248. $order = [
  249. 'user_id' => $userId,
  250. 'order_no' => $orderNo,
  251. 'money' => $money,
  252. 'total' => $total,
  253. 'after_money' => moneyFormat(max(0, $balance - $money), 2),
  254. 'actual_money' => $actualMoney,
  255. 'fee' => $fee,
  256. 'pool_money' => $poolMoney,
  257. 'pool_rate' => $poolRate,
  258. 'pt_money' => $ptMoney,
  259. 'pt_rate' => $ptRate,
  260. 'user_type' => $userType,
  261. 'type' => 2,
  262. 'account_type' => $accountType,
  263. 'pay_type' => $payType,
  264. 'realname' => $realname,
  265. 'account_name' => $accountName,
  266. 'account' => $account,
  267. 'account_remark' => $accountRemark,
  268. 'date' => date('Y-m-d'),
  269. 'create_time' => time(),
  270. 'status' => 1,
  271. 'mark' => 1
  272. ];
  273. if (!$orderId = $this->model::insertGetId($order)) {
  274. DB::rollBack();
  275. $this->error = '提现处理失败';
  276. RedisService::clear($cacheLockKey);
  277. return false;
  278. }
  279. $log = [
  280. 'user_id' => $userId,
  281. 'source_order_no' => $orderNo,
  282. 'user_type' => $userType,
  283. 'account_type' => $accountType,
  284. 'type' => 4,
  285. 'money' => -$money,
  286. 'after_money' => moneyFormat(max(0, $balance - $money), 2),
  287. 'date' => date('Y-m-d'),
  288. 'create_time' => time(),
  289. 'remark' => "提现到{$account}",
  290. 'status' => 1,
  291. 'mark' => 1,
  292. ];
  293. if (!$accountId = AccountLogModel::insertGetId($log)) {
  294. DB::rollBack();
  295. $this->error = '提现处理失败';
  296. RedisService::clear($cacheLockKey);
  297. return false;
  298. }
  299. DB::commit();
  300. // 操作日志
  301. ActionLogModel::setRecord($userId, ['type' => 2, 'title' => "{$accountTypeName}提现", 'content' => "姓名:{$realname},账号:{$accountName}/{$account}/{$accountRemark},提现{$money}元,单号:{$orderNo}", 'module' => 'balanceLog']);
  302. ActionLogModel::record();
  303. RedisService::clear($cacheLockKey);
  304. $this->error = '提现申请成功,请耐心等候审核~';
  305. return ['id' => $orderId, 'aid' => $accountId, 'money' => $money];
  306. }
  307. /**
  308. * 积分转账
  309. * @param $userId
  310. * @param $params
  311. * @return array|false
  312. */
  313. public function transfer($userId, $params)
  314. {
  315. // 参数验证
  316. $money = isset($params['money']) ? floatval($params['money']) : 0;
  317. $accountType = isset($params['type']) && $params['type']? intval($params['type']) : 3;
  318. $mobile = isset($params['mobile']) ? trim($params['mobile']) : '';
  319. $remark = isset($params['remark']) ? trim($params['remark']) : '';
  320. if ($money <= 0) {
  321. $this->error = '请输入转账数量';
  322. return false;
  323. }
  324. if (empty($mobile)) {
  325. $this->error = '请输入对方手机账号';
  326. return false;
  327. }
  328. $openTransfer = ConfigService::make()->getConfigByCode("transfer_{$accountType}_open", 1);
  329. if (!$openTransfer) {
  330. $this->error = '转账功能未开放';
  331. return false;
  332. }
  333. // 锁
  334. $cacheLockKey = "caches:members:transfer:{$userId}_{$accountType}";
  335. if (RedisService::get($cacheLockKey)) {
  336. $this->error = 1034;
  337. return false;
  338. }
  339. // 判断用户账号状态
  340. $fields = [2=>'property',3=>'bd_score',4=>'ls_score'];
  341. $field = isset($fields[$accountType])? $fields[$accountType]:'bd_score';
  342. RedisService::set($cacheLockKey, ['user_id' => $userId, 'params' => $params], rand(10, 20));
  343. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])
  344. ->select(['id', 'balance','mobile','nickname','property','bd_score','ls_score', 'status'])
  345. ->first();
  346. $realname = isset($userInfo['realname']) ? $userInfo['realname'] : '';
  347. $nickname = isset($userInfo['nickname']) ? $userInfo['nickname'] : '';
  348. $userMobile = isset($userInfo['mobile']) &&$userInfo['mobile']? $userInfo['mobile'] : '';
  349. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  350. $balance = isset($userInfo[$field]) ? $userInfo[$field] : 0;
  351. if (empty($userInfo) || $status != 1) {
  352. $this->error = 2016;
  353. RedisService::clear($cacheLockKey);
  354. return false;
  355. }
  356. if ($money > $balance) {
  357. $this->error = '该账户积分余额不足';
  358. RedisService::clear($cacheLockKey);
  359. return false;
  360. }
  361. $total = $money;
  362. $actualMoney = $money;
  363. $accountTypeName = ['账户','收益余额','数字资产','报单积分','绿色积分'][$accountType];
  364. $accountTypeName = $accountTypeName?$accountTypeName:'账户';
  365. // 对方账户验证
  366. $transferAccount = MemberModel::where(['mobile' => $mobile, 'mark' => 1])
  367. ->select(['id', 'balance','property','bd_score','ls_score', 'status'])
  368. ->first();
  369. $status = isset($transferAccount['status']) ? $transferAccount['status'] : 0;
  370. $transferBalance = isset($transferAccount[$field]) ? $transferAccount[$field] : 0;
  371. if (empty($transferAccount) || $status != 1) {
  372. $this->error = '对方账户不存在或已冻结';
  373. RedisService::clear($cacheLockKey);
  374. return false;
  375. }
  376. // 转账处理
  377. DB::beginTransaction();
  378. $updateData = ["{$field}" => DB::raw("{$field} - {$money}"), 'update_time' => time()];
  379. // 扣除会员账户
  380. if (!MemberModel::where(['id' => $userId])->update($updateData)) {
  381. DB::rollBack();
  382. $this->error = '转账处理失败';
  383. RedisService::clear($cacheLockKey);
  384. return false;
  385. }
  386. $updateData = ["{$field}" => DB::raw("{$field} + {$money}"), 'update_time' => time()];
  387. if (!MemberModel::where(['mobile' => $mobile])->update($updateData)) {
  388. DB::rollBack();
  389. $this->error = '转账处理失败';
  390. RedisService::clear($cacheLockKey);
  391. return false;
  392. }
  393. $orderNo = get_order_num('TS');
  394. $order = [
  395. 'user_id' => $userId,
  396. 'order_no' => $orderNo,
  397. 'money' => $money,
  398. 'total' => $total,
  399. 'after_money' => moneyFormat(max(0, $balance - $money), 2),
  400. 'actual_money' => $actualMoney,
  401. 'user_type' => 1,
  402. 'type' => 3,
  403. 'account_type' => $accountType,
  404. 'pay_type' => 30,
  405. 'realname' => '',
  406. 'account_name' => $accountTypeName,
  407. 'account' => $mobile,
  408. 'remark' => $remark,
  409. 'date' => date('Y-m-d'),
  410. 'create_time' => time(),
  411. 'status' => 4,
  412. 'mark' => 1
  413. ];
  414. if (!$orderId = $this->model::insertGetId($order)) {
  415. DB::rollBack();
  416. $this->error = '提现处理失败';
  417. RedisService::clear($cacheLockKey);
  418. return false;
  419. }
  420. $log = [
  421. 'user_id' => $userId,
  422. 'source_order_no' => $orderNo,
  423. 'user_type' => 1,
  424. 'account_type' => $accountType,
  425. 'type' => 9,
  426. 'money' => -$money,
  427. 'after_money' => moneyFormat(max(0, $balance - $money), 2),
  428. 'date' => date('Y-m-d'),
  429. 'create_time' => time(),
  430. 'remark' => "转账到{$mobile}",
  431. 'status' => 1,
  432. 'mark' => 1,
  433. ];
  434. if (!$accountId = AccountLogModel::insertGetId($log)) {
  435. DB::rollBack();
  436. $this->error = '转账处理失败';
  437. RedisService::clear($cacheLockKey);
  438. return false;
  439. }
  440. $userMobileText = $userMobile?format_mobile($userMobile):$nickname;
  441. $log = [
  442. 'user_id' => $userId,
  443. 'source_order_no' => $orderNo,
  444. 'user_type' => 1,
  445. 'account_type' => $accountType,
  446. 'type' => 9,
  447. 'money' => $money,
  448. 'after_money' => moneyFormat(max(0, $transferBalance + $money), 2),
  449. 'date' => date('Y-m-d'),
  450. 'create_time' => time(),
  451. 'remark' => "收到{$userMobileText}用户的{$accountTypeName}转账",
  452. 'status' => 1,
  453. 'mark' => 1,
  454. ];
  455. if (!$accountId = AccountLogModel::insertGetId($log)) {
  456. DB::rollBack();
  457. $this->error = '转账处理失败';
  458. RedisService::clear($cacheLockKey);
  459. return false;
  460. }
  461. DB::commit();
  462. // 操作日志
  463. ActionLogModel::setRecord($userId, ['type' => 2, 'title' => "{$accountTypeName}积分转账", 'content' => "账户{$userMobileText}转至{$mobile},数量{$money},单号:{$orderNo}", 'module' => 'balanceLog']);
  464. ActionLogModel::record();
  465. RedisService::clear($cacheLockKey);
  466. $this->error = '转账成功~';
  467. return ['id' => $orderId, 'aid' => $accountId, 'money' => $money];
  468. }
  469. }