BalanceLogService.php 20 KB

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