UserExtractServices.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace app\services\user;
  13. use app\jobs\system\CapitalFlowJob;
  14. use app\services\BaseServices;
  15. use app\dao\user\UserExtractDao;
  16. use app\services\order\StoreOrderCreateServices;
  17. use app\services\wechat\WechatUserServices;
  18. use crmeb\exceptions\AdminException;
  19. use crmeb\services\wechat\Payment;
  20. use crmeb\services\FormBuilder as Form;
  21. use crmeb\services\WithdrawService;
  22. use crmeb\traits\ServicesTrait;
  23. use think\exception\ValidateException;
  24. use think\facade\Route as Url;
  25. /**
  26. *
  27. * Class UserExtractServices
  28. * @package app\services\user
  29. * @mixin UserExtractDao
  30. */
  31. class UserExtractServices extends BaseServices
  32. {
  33. use ServicesTrait;
  34. /**
  35. * UserExtractServices constructor.
  36. * @param UserExtractDao $dao
  37. */
  38. public function __construct(UserExtractDao $dao)
  39. {
  40. $this->dao = $dao;
  41. }
  42. /**
  43. * 获取一条提现记录
  44. * @param int $id
  45. * @param array $field
  46. * @return array|\think\Model|null
  47. */
  48. public function getExtract(int $id, array $field = [])
  49. {
  50. return $this->dao->get($id, $field);
  51. }
  52. /**
  53. * 获取某个用户提现总数
  54. * @param int $uid
  55. * @return float
  56. */
  57. public function getUserExtract(int $uid)
  58. {
  59. return $this->dao->getWhereSum(['uid' => $uid, 'status' => [0, 1]]);
  60. }
  61. /**
  62. * 获取某些用户的提现总数列表
  63. * @param array $uids
  64. */
  65. public function getUsersSumList(array $uids)
  66. {
  67. return $this->dao->getWhereSumList(['uid' => $uids, 'status' => [0, 1]]);
  68. }
  69. public function getCount(array $where = [])
  70. {
  71. return $this->dao->getCount($where);
  72. }
  73. /**
  74. * 获取提现列表
  75. * @param array $where
  76. * @param string $field
  77. * @return array
  78. * @throws \think\db\exception\DataNotFoundException
  79. * @throws \think\db\exception\DbException
  80. * @throws \think\db\exception\ModelNotFoundException
  81. */
  82. public function getUserExtractList(array $where, string $field = '*')
  83. {
  84. [$page, $limit] = $this->getPageValue();
  85. $list = $this->dao->getExtractList($where, $field, $page, $limit);
  86. foreach ($list as &$item) {
  87. $item['nickname'] = $item['user']['nickname'] ?? '';
  88. }
  89. $count = $this->dao->count($where);
  90. return compact('list', 'count');
  91. }
  92. /**
  93. * 获取提现总数
  94. * @param array $where
  95. */
  96. public function getExtractSum(array $where)
  97. {
  98. return $this->dao->getExtractMoneyByWhere($where, 'extract_price');
  99. }
  100. /**
  101. * 拒绝提现申请
  102. * @param $id
  103. * @param $fail_msg
  104. * @return bool
  105. * @throws \think\db\exception\DataNotFoundException
  106. * @throws \think\db\exception\ModelNotFoundException
  107. * @throws \think\exception\DbException
  108. */
  109. public function changeFail(int $id, $userExtract, $message)
  110. {
  111. $fail_time = time();
  112. $extract_number = bcadd((string)$userExtract['extract_price'], (string)$userExtract['extract_fee'], 2);
  113. $mark = '提现失败,退回佣金' . $extract_number . '元';
  114. $uid = $userExtract['uid'];
  115. $status = -1;
  116. /** @var UserServices $userServices */
  117. $userServices = app()->make(UserServices::class);
  118. $user = $userServices->getUserInfo($uid);
  119. if (!$user) {
  120. throw new ValidateException('用户不存在');
  121. }
  122. /** @var UserBrokerageServices $userBrokerageServices */
  123. $userBrokerageServices = app()->make(UserBrokerageServices::class);
  124. $this->transaction(function () use ($user, $userBrokerageServices, $uid, $id, $extract_number, $message, $userServices, $status, $fail_time) {
  125. $now_brokerage = bcadd((string)$user['brokerage_price'], (string)$extract_number, 2);
  126. //增加佣金记录
  127. $userBrokerageServices->income('extract_fail', $uid, $extract_number, $now_brokerage, $id);
  128. //修改用户佣金
  129. if (!$userServices->update($uid, ['brokerage_price' => $now_brokerage], 'uid'))
  130. throw new AdminException('增加用户佣金失败');
  131. if (!$this->dao->update($id, ['fail_time' => $fail_time, 'fail_msg' => $message, 'status' => $status])) {
  132. throw new AdminException('修改失败');
  133. }
  134. });
  135. //消息推送
  136. event('notice.notice', [['uid' => $uid, 'userType' => strtolower($user['user_type']), 'extract_number' => $extract_number, 'nickname' => $user['nickname'], 'message' => $message], 'user_balance_change']);
  137. return true;
  138. }
  139. /**
  140. * 通过提现申请
  141. * @param $id
  142. * @return bool
  143. * @throws \think\db\exception\DataNotFoundException
  144. * @throws \think\db\exception\ModelNotFoundException
  145. * @throws \think\exception\DbException
  146. */
  147. public function changeSuccess(int $id, $userExtract)
  148. {
  149. $extractNumber = $userExtract['extract_price'];
  150. $this->transaction(function () use ($id, $userExtract, $extractNumber) {
  151. if ($userExtract['extract_type'] != 'bank') {
  152. if (!$this->dao->update($id, ['status' => 1])) {
  153. throw new AdminException('修改失败');
  154. }
  155. //配置开启自动到零钱
  156. if (sys_config('brokerage_type', 0)) {
  157. /** @var WechatUserServices $wechatServices */
  158. $wechatServices = app()->make(WechatUserServices::class);
  159. $openid = $wechatServices->getWechatOpenid((int)$userExtract['uid'], 'wechat');
  160. if ($openid) {//公众号用户
  161. $type = Payment::WEB;
  162. } else {//小程序用户
  163. $openid = $wechatServices->getWechatOpenid((int)$userExtract['uid'], 'routine');
  164. $type = Payment::MINI;
  165. }
  166. //app微信用户
  167. if (!$openid) {
  168. $openid = $wechatServices->getWechatOpenid((int)$userExtract['uid'], 'app');
  169. $type = Payment::APP;
  170. }
  171. if ($openid) {
  172. /** @var StoreOrderCreateServices $services */
  173. $services = app()->make(StoreOrderCreateServices::class);
  174. $wechat_order_id = $services->getNewOrderId();
  175. $res = Payment::merchantPay($openid, $wechat_order_id, $extractNumber, '提现佣金到零钱', $type);
  176. if (!$res) {
  177. throw new ValidateException('企业付款到零钱失败,请稍后再试');
  178. }
  179. } else {
  180. throw new ValidateException('该用户暂不支持企业付款到零钱,请手动转账');
  181. }
  182. }
  183. /** @var UserServices $userServices */
  184. $userServices = app()->make(UserServices::class);
  185. $userType = $userServices->value(['uid' => $userExtract['uid']], 'user_type');
  186. $nickname = $userServices->value(['uid' => $userExtract['uid']], 'nickname');
  187. $phone = $userServices->value(['uid' => $userExtract['uid']], 'phone');
  188. switch ($userExtract['extract_type']) {
  189. case 'bank':
  190. $order_id = $userExtract['bank_code'];
  191. break;
  192. case 'weixin':
  193. $order_id = $userExtract['wechat'];
  194. break;
  195. case 'alipay':
  196. $order_id = $userExtract['alipay_code'];
  197. break;
  198. default:
  199. $order_id = '';
  200. break;
  201. }
  202. //记录资金流水队列
  203. CapitalFlowJob::dispatch([['order_id' => $order_id, 'store_id' => 0, 'uid' => $userExtract['uid'], 'nickname' => $nickname, 'phone' => $phone, 'price' => $extractNumber, 'pay_type' => $userExtract['extract_type']], 'extract']);
  204. //消息推送
  205. event('notice.notice', [['uid' => $userExtract['uid'], 'userType' => strtolower($userType), 'extractNumber' => $extractNumber, 'nickname' => $nickname], 'user_extract']);
  206. } else {
  207. if (!$this->dao->update($id, ['status' => 2])) {
  208. throw new AdminException('修改失败');
  209. }
  210. $userServices = app()->make(UserServices::class);
  211. $userInfo = $userServices->get($userExtract['uid']);
  212. if (!$userInfo['professional_id']) {
  213. throw new ValidateException('用户未认证签约');
  214. }
  215. $bankInfo = WithdrawService::init()::contractInfo($userInfo['enterprise_professional_facilitator_id']);
  216. if (!$bankInfo['sign_img']) throw new ValidateException('用户未签约');
  217. $res = WithdrawService::init()::fastIssuing(
  218. $userInfo['professional_id'],
  219. $userExtract['id'],
  220. $bankInfo['name'],
  221. $bankInfo['cer_code'],
  222. $bankInfo['mobile'],
  223. $bankInfo['bank_code'],
  224. $extractNumber,
  225. '佣金提现'
  226. );
  227. if ($res) {
  228. $this->dao->update($id, ['trade_number' => $res['trade_number']]);
  229. }
  230. }
  231. });
  232. return true;
  233. }
  234. /**
  235. * 显示资源列表
  236. * @param array $where
  237. * @return array
  238. * @throws \think\db\exception\DataNotFoundException
  239. * @throws \think\db\exception\DbException
  240. * @throws \think\db\exception\ModelNotFoundException
  241. */
  242. public function index(array $where)
  243. {
  244. $list = $this->getUserExtractList($where);
  245. //待提现金额
  246. $where['status'] = 0;
  247. $extract_statistics['price'] = $this->getExtractSum($where);
  248. //已提现金额
  249. $where['status'] = 1;
  250. $extract_statistics['priced'] = $this->getExtractSum($where);
  251. //佣金总金额
  252. /** @var UserBrokerageServices $userBrokerageServices */
  253. $userBrokerageServices = app()->make(UserBrokerageServices::class);
  254. $extract_statistics['brokerage_count'] = $userBrokerageServices->getUsersBokerageSum(array_merge($where, ['pm' => 1, 'not_type' => ['extract_fail', 'refund']]));
  255. //未提现金额
  256. $extract_statistics['brokerage_not'] = $extract_statistics['brokerage_count'] > $extract_statistics['priced'] ? bcsub((string)$extract_statistics['brokerage_count'], (string)$extract_statistics['priced'], 2) : 0.00;
  257. return compact('extract_statistics', 'list');
  258. }
  259. /**
  260. * 显示编辑资源表单页.
  261. *
  262. * @param int $id
  263. * @return \think\Response
  264. */
  265. public function edit(int $id)
  266. {
  267. $UserExtract = $this->getExtract($id);
  268. if (!$UserExtract) {
  269. throw new AdminException('数据不存在!');
  270. }
  271. $f = array();
  272. $f[] = Form::input('real_name', '姓名', $UserExtract['real_name']);
  273. $f[] = Form::number('extract_price', '提现金额', (float)$UserExtract['extract_price'])->precision(2)->disabled(true);
  274. if ($UserExtract['extract_type'] == 'alipay') {
  275. $f[] = Form::input('alipay_code', '支付宝账号', $UserExtract['alipay_code']);
  276. } else if ($UserExtract['extract_type'] == 'weixin') {
  277. $f[] = Form::input('wechat', '微信号', $UserExtract['wechat']);
  278. } else {
  279. $f[] = Form::input('bank_code', '银行卡号', $UserExtract['bank_code']);
  280. $f[] = Form::input('bank_address', '开户行', $UserExtract['bank_address']);
  281. }
  282. $f[] = Form::input('mark', '备注', $UserExtract['mark'])->type('textarea');
  283. return create_form('编辑', $f, Url::buildUrl('/finance/extract/' . $id), 'PUT');
  284. }
  285. public function update(int $id, array $data)
  286. {
  287. if (!$this->dao->update($id, $data))
  288. throw new AdminException('修改失败');
  289. else
  290. return true;
  291. }
  292. /**
  293. * 拒绝
  294. * @param $id
  295. * @return mixed
  296. */
  297. public function refuse(int $id, string $message)
  298. {
  299. $extract = $this->getExtract($id);
  300. if (!$extract) {
  301. throw new AdminException('操作记录不存在!');
  302. }
  303. if ($extract->status == 1) {
  304. throw new AdminException('已经提现,错误操作');
  305. }
  306. if ($extract->status == -1) {
  307. throw new AdminException('您的提现申请已被拒绝,请勿重复操作!');
  308. }
  309. $res = $this->changeFail($id, $extract, $message);
  310. if ($res) {
  311. return true;
  312. } else {
  313. throw new AdminException('操作失败!');
  314. }
  315. }
  316. /**
  317. * 通过
  318. * @param $id
  319. * @return mixed
  320. */
  321. public function adopt(int $id)
  322. {
  323. $extract = $this->getExtract($id);
  324. if (!$extract) {
  325. throw new AdminException('操作记录不存!');
  326. }
  327. if ($extract->status == 1 || $extract->status == 2) {
  328. throw new AdminException('您已提现,请勿重复提现!');
  329. }
  330. if ($extract->status == -1) {
  331. throw new AdminException('您的提现申请已被拒绝!');
  332. }
  333. if ($this->changeSuccess($id, $extract)) {
  334. return true;
  335. } else {
  336. throw new AdminException('操作失败!');
  337. }
  338. }
  339. /**待提现的数量
  340. * @return int
  341. */
  342. public function userExtractCount()
  343. {
  344. return $this->dao->count(['status' => 0]);
  345. }
  346. /**
  347. * 银行卡提现
  348. * @param int $uid
  349. * @return mixed
  350. */
  351. public function bank(int $uid)
  352. {
  353. /** @var UserServices $userService */
  354. $userService = app()->make(UserServices::class);
  355. $user = $userService->getUserInfo($uid);
  356. if (!$user) {
  357. throw new ValidateException('数据不存在');
  358. }
  359. /** @var UserBrokerageServices $userBrokerageServices */
  360. $userBrokerageServices = app()->make(UserBrokerageServices::class);
  361. $data['broken_commission'] = $userBrokerageServices->getUserFrozenPrice($uid);
  362. if ($data['broken_commission'] < 0)
  363. $data['broken_commission'] = '0';
  364. $data['brokerage_price'] = $user['brokerage_price'];
  365. //可提现佣金
  366. $data['commissionCount'] = bcsub((string)$data['brokerage_price'], (string)$data['broken_commission'], 2);
  367. $extractBank = sys_config('user_extract_bank') ?? []; //提现银行
  368. $extractBank = str_replace("\r\n", "\n", $extractBank);//防止不兼容
  369. $data['extractBank'] = explode("\n", is_array($extractBank) ? (isset($extractBank[0]) ? $extractBank[0] : $extractBank) : $extractBank);
  370. $data['minPrice'] = sys_config('user_extract_min_price');//提现最低金额
  371. $data['withdraw_fee'] = sys_config('withdraw_fee');//提现手续费
  372. $data['extract_wechat_type'] = sys_config('brokerage_type');//微信提现到账方式
  373. return $data;
  374. }
  375. /**
  376. * 提现申请
  377. * @param int $uid
  378. * @param array $data
  379. */
  380. public function cash(int $uid, array $data)
  381. {
  382. /** @var UserServices $userService */
  383. $userService = app()->make(UserServices::class);
  384. $user = $userService->getUserInfo($uid);
  385. if (!$user) {
  386. throw new ValidateException('数据不存在');
  387. }
  388. if (!$user['enterprise_professional_facilitator_id']) {
  389. throw new ValidateException('签约未完成');
  390. }
  391. $bank_info = WithdrawService::init()::contractInfo($user['enterprise_professional_facilitator_id']);
  392. if (!$bank_info['sign_img']) {
  393. throw new ValidateException('签约未完成');
  394. }
  395. $data['cardnum'] = $bank_info['bank_code'];
  396. $data['bankname'] = '灵活用工提现';
  397. /** @var UserBrokerageServices $userBrokerageServices */
  398. $userBrokerageServices = app()->make(UserBrokerageServices::class);
  399. $data['broken_commission'] = $userBrokerageServices->getUserFrozenPrice($uid);
  400. if ($data['broken_commission'] < 0)
  401. $data['broken_commission'] = 0;
  402. $data['brokerage_price'] = $user['brokerage_price'];
  403. //可提现佣金
  404. $commissionCount = (float)bcsub((string)$data['brokerage_price'], (string)$data['broken_commission'], 2);
  405. if ($data['money'] > $commissionCount) {
  406. throw new ValidateException('可提现佣金不足');
  407. }
  408. $extractPrice = $user['brokerage_price'];
  409. $userExtractMinPrice = sys_config('user_extract_min_price');
  410. if ($data['money'] < $userExtractMinPrice) {
  411. throw new ValidateException('提现金额不能小于' . $userExtractMinPrice . '元');
  412. }
  413. if ($extractPrice < 0) {
  414. throw new ValidateException('提现佣金不足' . $data['money']);
  415. }
  416. if ($data['money'] > $extractPrice) {
  417. throw new ValidateException('提现佣金不足' . $data['money']);
  418. }
  419. if ($data['money'] <= 0) {
  420. throw new ValidateException('提现佣金大于0');
  421. }
  422. $extract_fee = bcmul((string)$data['money'], bcdiv(sys_config('withdraw_fee'), '100', 2), 2);
  423. $insertData = [
  424. 'uid' => $user['uid'],
  425. 'extract_type' => $data['extract_type'],
  426. 'extract_price' => bcsub((string)$data['money'], (string)$extract_fee, 2),
  427. 'extract_fee' => $extract_fee,
  428. 'add_time' => time(),
  429. 'balance' => $user['brokerage_price'],
  430. 'status' => 0
  431. ];
  432. if (isset($data['name']) && strlen(trim($data['name']))) $insertData['real_name'] = $data['name'];
  433. else $insertData['real_name'] = $user['nickname'];
  434. if (isset($data['cardnum'])) $insertData['bank_code'] = $data['cardnum'];
  435. else $insertData['bank_code'] = '';
  436. if (isset($data['bankname'])) $insertData['bank_address'] = $data['bankname'];
  437. else $insertData['bank_address'] = '';
  438. if (isset($data['weixin'])) $insertData['wechat'] = $data['weixin'];
  439. else $insertData['wechat'] = $user['nickname'];
  440. if ($data['extract_type'] == 'alipay') {
  441. $insertData['alipay_code'] = $data['alipay_code'];
  442. $insertData['qrcode_url'] = $data['qrcode_url'];
  443. $mark = '使用支付宝';
  444. } else if ($data['extract_type'] == 'bank') {
  445. $mark = '使用银联卡' . $insertData['bank_code'];
  446. } else if ($data['extract_type'] == 'weixin') {
  447. $insertData['qrcode_url'] = $data['qrcode_url'];
  448. $mark = '使用微信提现';
  449. /** @var WechatUserServices $wechatServices */
  450. $wechatServices = app()->make(WechatUserServices::class);
  451. $openid = $wechatServices->getWechatOpenid($uid, 'wechat');
  452. if (sys_config('brokerage_type', 0) && $openid) {
  453. if ($insertData['extract_price'] < 1) {
  454. throw new ValidateException('扣除手续费后,提现金额不足1元;而企业微信付款到零钱最低金额为1元');
  455. }
  456. }
  457. }
  458. /** @var UserBrokerageServices $userBrokerageServices */
  459. $userBrokerageServices = app()->make(UserBrokerageServices::class);
  460. $res1 = $this->transaction(function () use ($insertData, $data, $uid, $userService, $user, $userBrokerageServices, $mark) {
  461. if (!$res1 = $this->dao->save($insertData)) {
  462. throw new ValidateException('提现失败');
  463. }
  464. //修改用户佣金
  465. $balance = bcsub((string)$user['brokerage_price'], (string)$data['money'], 2) ?? 0;
  466. if (!$userService->update($uid, ['brokerage_price' => $balance], 'uid')) {
  467. throw new ValidateException('修改用户信息失败');
  468. }
  469. //保存佣金记录
  470. $userBrokerageServices->income('extract', $uid, ['mark' => $mark, 'number' => $data['money']], $balance, $res1['id']);
  471. return $res1;
  472. });
  473. //用户申请体现事件
  474. event('user.extract', [$user, $data, $res1]);
  475. return true;
  476. }
  477. /**
  478. * @param array $where
  479. * @param string $SumField
  480. * @param string $selectType
  481. * @param string $group
  482. * @return float|mixed
  483. */
  484. public function getOutMoneyByWhere(array $where, string $SumField, string $selectType, string $group = "")
  485. {
  486. switch ($selectType) {
  487. case "sum" :
  488. return $this->dao->getWhereSumField($where, $SumField);
  489. case "group" :
  490. return $this->dao->getGroupField($where, $SumField, $group);
  491. }
  492. }
  493. }