BalanceLogService.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  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. $withdrawQuota = intval($mealPrice/0.27 * 0.73/100)*100;
  209. if($money>$withdrawQuota){
  210. $this->error = "抱歉您的账号可提现额度为:{$withdrawQuota}元";
  211. RedisService::clear($cacheLockKey);
  212. return false;
  213. }
  214. if ($money > $balance) {
  215. $this->error = '该账户可提现余额不足';
  216. RedisService::clear($cacheLockKey);
  217. return false;
  218. }
  219. // 计算实际到账金额
  220. $poolMoney = 0;
  221. $ptMoney = 0;
  222. $ptRate = 0;
  223. $poolRate = 0;
  224. $total = $money;
  225. $actualMoney = $money;
  226. if($accountType==2){
  227. // 提现金额
  228. $price = PriceService::make()->getTodayPrice(1);
  229. if($price<=0){
  230. $this->error = '请等候今日资产价格刷新后重试~';
  231. RedisService::clear($cacheLockKey);
  232. return false;
  233. }
  234. // 结算比例
  235. $rate = ConfigService::make()->getConfigByCode('withdraw_2_rate',0);
  236. $rate = $rate>0 && $rate<=100? $rate : 100;
  237. $total = moneyFormat($total * $price,2);
  238. $actualMoney = moneyFormat($total * $rate/100, 2);
  239. // 底池比例
  240. $poolRate = ConfigService::make()->getConfigByCode('withdraw_2_back_rate',0);
  241. $poolRate = $poolRate>0 && $poolRate<50? $poolRate : 0;
  242. $poolMoney = round($total * $poolRate/100, 2);
  243. // 运营账户比例
  244. $ptRate = ConfigService::make()->getConfigByCode('withdraw_2_pt_rate',0);
  245. $ptRate = $ptRate>0 && $ptRate<=50? $ptRate : 0;
  246. $ptMoney = round($total * $ptRate/100, 2);
  247. }
  248. // 手续费
  249. $feeRate = ConfigService::make()->getConfigByCode("withdraw_{$accountType}_fee",0);
  250. $feeRate = $feeRate>0 && $feeRate<=50? $feeRate : 0;
  251. $fee = round($actualMoney * $feeRate/100, 2);
  252. $actualMoney = moneyFormat($actualMoney - $fee, 2);
  253. $accountTypeName = ['账户','收益余额','数字资产','报单积分','绿色积分'][$accountType];
  254. $accountTypeName = $accountTypeName?$accountTypeName:'账户';
  255. // 提现处理
  256. DB::beginTransaction();
  257. $updateData = ["{$field}" => DB::raw("{$field} - {$money}"), 'update_time' => time()];
  258. // 会员账户
  259. $userType = 1;
  260. if (!MemberModel::where(['id' => $userId])->update($updateData)) {
  261. DB::rollBack();
  262. $this->error = '提现处理失败';
  263. RedisService::clear($cacheLockKey);
  264. return false;
  265. }
  266. $orderNo = get_order_num('JW');
  267. $order = [
  268. 'user_id' => $userId,
  269. 'order_no' => $orderNo,
  270. 'money' => $money,
  271. 'total' => $total,
  272. 'after_money' => moneyFormat(max(0, $balance - $money), 2),
  273. 'actual_money' => $actualMoney,
  274. 'fee' => $fee,
  275. 'pool_money' => $poolMoney,
  276. 'pool_rate' => $poolRate,
  277. 'pt_money' => $ptMoney,
  278. 'pt_rate' => $ptRate,
  279. 'user_type' => $userType,
  280. 'type' => 2,
  281. 'account_type' => $accountType,
  282. 'pay_type' => $payType,
  283. 'realname' => $realname,
  284. 'account_name' => $accountName,
  285. 'account' => $account,
  286. 'account_remark' => $accountRemark,
  287. 'date' => date('Y-m-d'),
  288. 'create_time' => time(),
  289. 'status' => 1,
  290. 'mark' => 1
  291. ];
  292. if (!$orderId = $this->model::insertGetId($order)) {
  293. DB::rollBack();
  294. $this->error = '提现处理失败';
  295. RedisService::clear($cacheLockKey);
  296. return false;
  297. }
  298. $log = [
  299. 'user_id' => $userId,
  300. 'source_order_no' => $orderNo,
  301. 'user_type' => $userType,
  302. 'account_type' => $accountType,
  303. 'type' => 4,
  304. 'money' => -$money,
  305. 'after_money' => moneyFormat(max(0, $balance - $money), 2),
  306. 'date' => date('Y-m-d'),
  307. 'create_time' => time(),
  308. 'remark' => "提现到{$account}",
  309. 'status' => 1,
  310. 'mark' => 1,
  311. ];
  312. if (!$accountId = AccountLogModel::insertGetId($log)) {
  313. DB::rollBack();
  314. $this->error = '提现处理失败';
  315. RedisService::clear($cacheLockKey);
  316. return false;
  317. }
  318. DB::commit();
  319. // 操作日志
  320. ActionLogModel::setRecord($userId, ['type' => 2, 'title' => "{$accountTypeName}提现", 'content' => "姓名:{$realname},账号:{$accountName}/{$account}/{$accountRemark},提现{$money}元,单号:{$orderNo}", 'module' => 'balanceLog']);
  321. ActionLogModel::record();
  322. RedisService::clear($cacheLockKey);
  323. $this->error = '提现申请成功,请耐心等候审核~';
  324. return ['id' => $orderId, 'aid' => $accountId, 'money' => $money];
  325. }
  326. /**
  327. * 积分转账
  328. * @param $userId
  329. * @param $params
  330. * @return array|false
  331. */
  332. public function transfer($userId, $params)
  333. {
  334. // 参数验证
  335. $money = isset($params['money']) ? floatval($params['money']) : 0;
  336. $accountType = isset($params['type']) && $params['type']? intval($params['type']) : 3;
  337. $mobile = isset($params['mobile']) ? trim($params['mobile']) : '';
  338. $remark = isset($params['remark']) ? trim($params['remark']) : '';
  339. if ($money <= 0) {
  340. $this->error = '请输入转账数量';
  341. return false;
  342. }
  343. if (empty($mobile)) {
  344. $this->error = '请输入对方手机账号';
  345. return false;
  346. }
  347. $openTransfer = ConfigService::make()->getConfigByCode("transfer_{$accountType}_open", 1);
  348. if (!$openTransfer) {
  349. $this->error = '转账功能未开放';
  350. return false;
  351. }
  352. // 锁
  353. $cacheLockKey = "caches:members:transfer:{$userId}_{$accountType}";
  354. if (RedisService::get($cacheLockKey)) {
  355. $this->error = 1034;
  356. return false;
  357. }
  358. // 判断用户账号状态
  359. $fields = [2=>'property',3=>'bd_score',4=>'ls_score'];
  360. $field = isset($fields[$accountType])? $fields[$accountType]:'bd_score';
  361. RedisService::set($cacheLockKey, ['user_id' => $userId, 'params' => $params], rand(10, 20));
  362. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])
  363. ->select(['id', 'balance','mobile','nickname','property','bd_score','ls_score', 'status'])
  364. ->first();
  365. $realname = isset($userInfo['realname']) ? $userInfo['realname'] : '';
  366. $nickname = isset($userInfo['nickname']) ? $userInfo['nickname'] : '';
  367. $userMobile = isset($userInfo['mobile']) &&$userInfo['mobile']? $userInfo['mobile'] : '';
  368. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  369. $balance = isset($userInfo[$field]) ? $userInfo[$field] : 0;
  370. if (empty($userInfo) || $status != 1) {
  371. $this->error = 2016;
  372. RedisService::clear($cacheLockKey);
  373. return false;
  374. }
  375. if ($money > $balance) {
  376. $this->error = '该账户积分余额不足';
  377. RedisService::clear($cacheLockKey);
  378. return false;
  379. }
  380. $total = $money;
  381. $actualMoney = $money;
  382. $accountTypeName = ['账户','收益余额','数字资产','报单积分','绿色积分'][$accountType];
  383. $accountTypeName = $accountTypeName?$accountTypeName:'账户';
  384. // 对方账户验证
  385. $transferAccount = MemberModel::where(['mobile' => $mobile, 'mark' => 1])
  386. ->select(['id', 'balance','property','bd_score','ls_score', 'status'])
  387. ->first();
  388. $transferUserId = isset($transferAccount['id']) ? $transferAccount['id'] : 0;
  389. $status = isset($transferAccount['status']) ? $transferAccount['status'] : 0;
  390. $transferBalance = isset($transferAccount[$field]) ? $transferAccount[$field] : 0;
  391. if (empty($transferAccount) || $status != 1 || $transferUserId<=0) {
  392. $this->error = '对方账户不存在或已冻结';
  393. RedisService::clear($cacheLockKey);
  394. return false;
  395. }
  396. // 转账处理
  397. DB::beginTransaction();
  398. $updateData = ["{$field}" => DB::raw("{$field} - {$money}"), 'update_time' => time()];
  399. // 扣除会员账户
  400. if (!MemberModel::where(['id' => $userId])->update($updateData)) {
  401. DB::rollBack();
  402. $this->error = '转账处理失败';
  403. RedisService::clear($cacheLockKey);
  404. return false;
  405. }
  406. $updateData = ["{$field}" => DB::raw("{$field} + {$money}"), 'update_time' => time()];
  407. if (!MemberModel::where(['mobile' => $mobile])->update($updateData)) {
  408. DB::rollBack();
  409. $this->error = '转账处理失败';
  410. RedisService::clear($cacheLockKey);
  411. return false;
  412. }
  413. $orderNo = get_order_num('TS');
  414. $order = [
  415. 'user_id' => $userId,
  416. 'order_no' => $orderNo,
  417. 'money' => $money,
  418. 'total' => $total,
  419. 'after_money' => moneyFormat(max(0, $balance - $money), 2),
  420. 'actual_money' => $actualMoney,
  421. 'user_type' => 1,
  422. 'type' => 3,
  423. 'account_type' => $accountType,
  424. 'pay_type' => 30,
  425. 'realname' => '',
  426. 'account_name' => $accountTypeName,
  427. 'account' => $mobile,
  428. 'remark' => $remark,
  429. 'date' => date('Y-m-d'),
  430. 'create_time' => time(),
  431. 'status' => 4,
  432. 'mark' => 1
  433. ];
  434. if (!$orderId = $this->model::insertGetId($order)) {
  435. DB::rollBack();
  436. $this->error = '提现处理失败';
  437. RedisService::clear($cacheLockKey);
  438. return false;
  439. }
  440. $log = [
  441. 'user_id' => $userId,
  442. 'source_order_no' => $orderNo,
  443. 'user_type' => 1,
  444. 'account_type' => $accountType,
  445. 'type' => 9,
  446. 'money' => -$money,
  447. 'after_money' => moneyFormat(max(0, $balance - $money), 2),
  448. 'date' => date('Y-m-d'),
  449. 'create_time' => time(),
  450. 'remark' => "转账到{$mobile}",
  451. 'status' => 1,
  452. 'mark' => 1,
  453. ];
  454. if (!$accountId = AccountLogModel::insertGetId($log)) {
  455. DB::rollBack();
  456. $this->error = '转账处理失败';
  457. RedisService::clear($cacheLockKey);
  458. return false;
  459. }
  460. $userMobileText = $userMobile?format_mobile($userMobile):$nickname;
  461. $log = [
  462. 'user_id' => $transferUserId,
  463. 'source_order_no' => $orderNo,
  464. 'user_type' => 1,
  465. 'account_type' => $accountType,
  466. 'type' => 9,
  467. 'money' => $money,
  468. 'after_money' => moneyFormat(max(0, $transferBalance + $money), 2),
  469. 'date' => date('Y-m-d'),
  470. 'create_time' => time(),
  471. 'remark' => "收到{$userMobileText}用户的{$accountTypeName}转账",
  472. 'status' => 1,
  473. 'mark' => 1,
  474. ];
  475. if (!AccountLogModel::insertGetId($log)) {
  476. DB::rollBack();
  477. $this->error = '转账处理失败';
  478. RedisService::clear($cacheLockKey);
  479. return false;
  480. }
  481. DB::commit();
  482. // 操作日志
  483. ActionLogModel::setRecord($userId, ['type' => 2, 'title' => "{$accountTypeName}积分转账", 'content' => "账户{$userMobileText}转至{$mobile},数量{$money},单号:{$orderNo}", 'module' => 'balanceLog']);
  484. ActionLogModel::record();
  485. RedisService::clear($cacheLockKey);
  486. $this->error = '转账成功~';
  487. return ['id' => $orderId, 'aid' => $accountId, 'money' => $money];
  488. }
  489. }