UserExtractServices.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  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 (!$this->dao->update($id, ['status' => 1])) {
  152. throw new AdminException('修改失败');
  153. }
  154. //配置开启自动到零钱
  155. if (sys_config('brokerage_type', 0)) {
  156. /** @var WechatUserServices $wechatServices */
  157. $wechatServices = app()->make(WechatUserServices::class);
  158. $openid = $wechatServices->getWechatOpenid((int)$userExtract['uid'], 'wechat');
  159. if ($openid) {//公众号用户
  160. $type = Payment::WEB;
  161. } else {//小程序用户
  162. $openid = $wechatServices->getWechatOpenid((int)$userExtract['uid'], 'routine');
  163. $type = Payment::MINI;
  164. }
  165. //app微信用户
  166. if (!$openid) {
  167. $openid = $wechatServices->getWechatOpenid((int)$userExtract['uid'], 'app');
  168. $type = Payment::APP;
  169. }
  170. if ($openid) {
  171. /** @var StoreOrderCreateServices $services */
  172. $services = app()->make(StoreOrderCreateServices::class);
  173. $wechat_order_id = $services->getNewOrderId();
  174. $res = Payment::merchantPay($openid, $wechat_order_id, $extractNumber, '提现佣金到零钱', $type);
  175. if (!$res) {
  176. throw new ValidateException('企业付款到零钱失败,请稍后再试');
  177. }
  178. } else {
  179. throw new ValidateException('该用户暂不支持企业付款到零钱,请手动转账');
  180. }
  181. } else {
  182. if ($userExtract['extract_type'] == 'bank') {
  183. $userServices = app()->make(UserServices::class);
  184. $userInfo = $userServices->get($userExtract['uid']);
  185. if (!$userInfo['professional_id']) {
  186. throw new ValidateException('用户未认证签约');
  187. }
  188. $bankInfo = WithdrawService::init()::contractInfo($userInfo['enterprise_professional_facilitator_id']);
  189. if (!$bankInfo['sign_img']) throw new ValidateException('用户未签约');
  190. $res = WithdrawService::init()::fastIssuing(
  191. $userInfo['professional_id'],
  192. $userExtract['id'],
  193. $bankInfo['name'],
  194. $bankInfo['cer_code'],
  195. $bankInfo['mobile'],
  196. $bankInfo['bank_code'],
  197. $extractNumber,
  198. '佣金提现'
  199. );
  200. if ($res) {
  201. $this->dao->update($id, ['trade_number' => $res['trade_number']]);
  202. }
  203. }
  204. }
  205. });
  206. /** @var UserServices $userServices */
  207. $userServices = app()->make(UserServices::class);
  208. $userType = $userServices->value(['uid' => $userExtract['uid']], 'user_type');
  209. $nickname = $userServices->value(['uid' => $userExtract['uid']], 'nickname');
  210. $phone = $userServices->value(['uid' => $userExtract['uid']], 'phone');
  211. switch ($userExtract['extract_type']) {
  212. case 'bank':
  213. $order_id = $userExtract['bank_code'];
  214. break;
  215. case 'weixin':
  216. $order_id = $userExtract['wechat'];
  217. break;
  218. case 'alipay':
  219. $order_id = $userExtract['alipay_code'];
  220. break;
  221. default:
  222. $order_id = '';
  223. break;
  224. }
  225. //记录资金流水队列
  226. CapitalFlowJob::dispatch([['order_id' => $order_id, 'store_id' => 0, 'uid' => $userExtract['uid'], 'nickname' => $nickname, 'phone' => $phone, 'price' => $extractNumber, 'pay_type' => $userExtract['extract_type']], 'extract']);
  227. //消息推送
  228. event('notice.notice', [['uid' => $userExtract['uid'], 'userType' => strtolower($userType), 'extractNumber' => $extractNumber, 'nickname' => $nickname], 'user_extract']);
  229. return true;
  230. }
  231. /**
  232. * 显示资源列表
  233. * @param array $where
  234. * @return array
  235. * @throws \think\db\exception\DataNotFoundException
  236. * @throws \think\db\exception\DbException
  237. * @throws \think\db\exception\ModelNotFoundException
  238. */
  239. public function index(array $where)
  240. {
  241. $list = $this->getUserExtractList($where);
  242. //待提现金额
  243. $where['status'] = 0;
  244. $extract_statistics['price'] = $this->getExtractSum($where);
  245. //已提现金额
  246. $where['status'] = 1;
  247. $extract_statistics['priced'] = $this->getExtractSum($where);
  248. //佣金总金额
  249. /** @var UserBrokerageServices $userBrokerageServices */
  250. $userBrokerageServices = app()->make(UserBrokerageServices::class);
  251. $extract_statistics['brokerage_count'] = $userBrokerageServices->getUsersBokerageSum(array_merge($where, ['pm' => 1, 'not_type' => ['extract_fail', 'refund']]));
  252. //未提现金额
  253. $extract_statistics['brokerage_not'] = $extract_statistics['brokerage_count'] > $extract_statistics['priced'] ? bcsub((string)$extract_statistics['brokerage_count'], (string)$extract_statistics['priced'], 2) : 0.00;
  254. return compact('extract_statistics', 'list');
  255. }
  256. /**
  257. * 显示编辑资源表单页.
  258. *
  259. * @param int $id
  260. * @return \think\Response
  261. */
  262. public function edit(int $id)
  263. {
  264. $UserExtract = $this->getExtract($id);
  265. if (!$UserExtract) {
  266. throw new AdminException('数据不存在!');
  267. }
  268. $f = array();
  269. $f[] = Form::input('real_name', '姓名', $UserExtract['real_name']);
  270. $f[] = Form::number('extract_price', '提现金额', (float)$UserExtract['extract_price'])->precision(2)->disabled(true);
  271. if ($UserExtract['extract_type'] == 'alipay') {
  272. $f[] = Form::input('alipay_code', '支付宝账号', $UserExtract['alipay_code']);
  273. } else if ($UserExtract['extract_type'] == 'weixin') {
  274. $f[] = Form::input('wechat', '微信号', $UserExtract['wechat']);
  275. } else {
  276. $f[] = Form::input('bank_code', '银行卡号', $UserExtract['bank_code']);
  277. $f[] = Form::input('bank_address', '开户行', $UserExtract['bank_address']);
  278. }
  279. $f[] = Form::input('mark', '备注', $UserExtract['mark'])->type('textarea');
  280. return create_form('编辑', $f, Url::buildUrl('/finance/extract/' . $id), 'PUT');
  281. }
  282. public function update(int $id, array $data)
  283. {
  284. if (!$this->dao->update($id, $data))
  285. throw new AdminException('修改失败');
  286. else
  287. return true;
  288. }
  289. /**
  290. * 拒绝
  291. * @param $id
  292. * @return mixed
  293. */
  294. public function refuse(int $id, string $message)
  295. {
  296. $extract = $this->getExtract($id);
  297. if (!$extract) {
  298. throw new AdminException('操作记录不存在!');
  299. }
  300. if ($extract->status == 1) {
  301. throw new AdminException('已经提现,错误操作');
  302. }
  303. if ($extract->status == -1) {
  304. throw new AdminException('您的提现申请已被拒绝,请勿重复操作!');
  305. }
  306. $res = $this->changeFail($id, $extract, $message);
  307. if ($res) {
  308. return true;
  309. } else {
  310. throw new AdminException('操作失败!');
  311. }
  312. }
  313. /**
  314. * 通过
  315. * @param $id
  316. * @return mixed
  317. */
  318. public function adopt(int $id)
  319. {
  320. $extract = $this->getExtract($id);
  321. if (!$extract) {
  322. throw new AdminException('操作记录不存!');
  323. }
  324. if ($extract->status == 1) {
  325. throw new AdminException('您已提现,请勿重复提现!');
  326. }
  327. if ($extract->status == -1) {
  328. throw new AdminException('您的提现申请已被拒绝!');
  329. }
  330. if ($this->changeSuccess($id, $extract)) {
  331. return true;
  332. } else {
  333. throw new AdminException('操作失败!');
  334. }
  335. }
  336. /**待提现的数量
  337. * @return int
  338. */
  339. public function userExtractCount()
  340. {
  341. return $this->dao->count(['status' => 0]);
  342. }
  343. /**
  344. * 银行卡提现
  345. * @param int $uid
  346. * @return mixed
  347. */
  348. public function bank(int $uid)
  349. {
  350. /** @var UserServices $userService */
  351. $userService = app()->make(UserServices::class);
  352. $user = $userService->getUserInfo($uid);
  353. if (!$user) {
  354. throw new ValidateException('数据不存在');
  355. }
  356. /** @var UserBrokerageServices $userBrokerageServices */
  357. $userBrokerageServices = app()->make(UserBrokerageServices::class);
  358. $data['broken_commission'] = $userBrokerageServices->getUserFrozenPrice($uid);
  359. if ($data['broken_commission'] < 0)
  360. $data['broken_commission'] = '0';
  361. $data['brokerage_price'] = $user['brokerage_price'];
  362. //可提现佣金
  363. $data['commissionCount'] = bcsub((string)$data['brokerage_price'], (string)$data['broken_commission'], 2);
  364. $extractBank = sys_config('user_extract_bank') ?? []; //提现银行
  365. $extractBank = str_replace("\r\n", "\n", $extractBank);//防止不兼容
  366. $data['extractBank'] = explode("\n", is_array($extractBank) ? (isset($extractBank[0]) ? $extractBank[0] : $extractBank) : $extractBank);
  367. $data['minPrice'] = sys_config('user_extract_min_price');//提现最低金额
  368. $data['withdraw_fee'] = sys_config('withdraw_fee');//提现手续费
  369. $data['extract_wechat_type'] = sys_config('brokerage_type');//微信提现到账方式
  370. return $data;
  371. }
  372. /**
  373. * 提现申请
  374. * @param int $uid
  375. * @param array $data
  376. */
  377. public function cash(int $uid, array $data)
  378. {
  379. /** @var UserServices $userService */
  380. $userService = app()->make(UserServices::class);
  381. $user = $userService->getUserInfo($uid);
  382. if (!$user) {
  383. throw new ValidateException('数据不存在');
  384. }
  385. if (!$user['enterprise_professional_facilitator_id']) {
  386. throw new ValidateException('签约未完成');
  387. }
  388. $bank_info = WithdrawService::init()::contractInfo($user['enterprise_professional_facilitator_id']);
  389. if (!$bank_info['sign_img']) {
  390. throw new ValidateException('签约未完成');
  391. }
  392. $data['cardnum'] = $bank_info['bank_code'];
  393. $data['bankname'] = '灵活用工提现';
  394. /** @var UserBrokerageServices $userBrokerageServices */
  395. $userBrokerageServices = app()->make(UserBrokerageServices::class);
  396. $data['broken_commission'] = $userBrokerageServices->getUserFrozenPrice($uid);
  397. if ($data['broken_commission'] < 0)
  398. $data['broken_commission'] = 0;
  399. $data['brokerage_price'] = $user['brokerage_price'];
  400. //可提现佣金
  401. $commissionCount = (float)bcsub((string)$data['brokerage_price'], (string)$data['broken_commission'], 2);
  402. if ($data['money'] > $commissionCount) {
  403. throw new ValidateException('可提现佣金不足');
  404. }
  405. $extractPrice = $user['brokerage_price'];
  406. $userExtractMinPrice = sys_config('user_extract_min_price');
  407. if ($data['money'] < $userExtractMinPrice) {
  408. throw new ValidateException('提现金额不能小于' . $userExtractMinPrice . '元');
  409. }
  410. if ($extractPrice < 0) {
  411. throw new ValidateException('提现佣金不足' . $data['money']);
  412. }
  413. if ($data['money'] > $extractPrice) {
  414. throw new ValidateException('提现佣金不足' . $data['money']);
  415. }
  416. if ($data['money'] <= 0) {
  417. throw new ValidateException('提现佣金大于0');
  418. }
  419. $extract_fee = bcmul((string)$data['money'], bcdiv(sys_config('withdraw_fee'), '100', 2), 2);
  420. $insertData = [
  421. 'uid' => $user['uid'],
  422. 'extract_type' => $data['extract_type'],
  423. 'extract_price' => bcsub((string)$data['money'], (string)$extract_fee, 2),
  424. 'extract_fee' => $extract_fee,
  425. 'add_time' => time(),
  426. 'balance' => $user['brokerage_price'],
  427. 'status' => 0
  428. ];
  429. if (isset($data['name']) && strlen(trim($data['name']))) $insertData['real_name'] = $data['name'];
  430. else $insertData['real_name'] = $user['nickname'];
  431. if (isset($data['cardnum'])) $insertData['bank_code'] = $data['cardnum'];
  432. else $insertData['bank_code'] = '';
  433. if (isset($data['bankname'])) $insertData['bank_address'] = $data['bankname'];
  434. else $insertData['bank_address'] = '';
  435. if (isset($data['weixin'])) $insertData['wechat'] = $data['weixin'];
  436. else $insertData['wechat'] = $user['nickname'];
  437. if ($data['extract_type'] == 'alipay') {
  438. $insertData['alipay_code'] = $data['alipay_code'];
  439. $insertData['qrcode_url'] = $data['qrcode_url'];
  440. $mark = '使用支付宝';
  441. } else if ($data['extract_type'] == 'bank') {
  442. $mark = '使用银联卡' . $insertData['bank_code'];
  443. } else if ($data['extract_type'] == 'weixin') {
  444. $insertData['qrcode_url'] = $data['qrcode_url'];
  445. $mark = '使用微信提现';
  446. /** @var WechatUserServices $wechatServices */
  447. $wechatServices = app()->make(WechatUserServices::class);
  448. $openid = $wechatServices->getWechatOpenid($uid, 'wechat');
  449. if (sys_config('brokerage_type', 0) && $openid) {
  450. if ($insertData['extract_price'] < 1) {
  451. throw new ValidateException('扣除手续费后,提现金额不足1元;而企业微信付款到零钱最低金额为1元');
  452. }
  453. }
  454. }
  455. /** @var UserBrokerageServices $userBrokerageServices */
  456. $userBrokerageServices = app()->make(UserBrokerageServices::class);
  457. $res1 = $this->transaction(function () use ($insertData, $data, $uid, $userService, $user, $userBrokerageServices, $mark) {
  458. if (!$res1 = $this->dao->save($insertData)) {
  459. throw new ValidateException('提现失败');
  460. }
  461. //修改用户佣金
  462. $balance = bcsub((string)$user['brokerage_price'], (string)$data['money'], 2) ?? 0;
  463. if (!$userService->update($uid, ['brokerage_price' => $balance], 'uid')) {
  464. throw new ValidateException('修改用户信息失败');
  465. }
  466. //保存佣金记录
  467. $userBrokerageServices->income('extract', $uid, ['mark' => $mark, 'number' => $data['money']], $balance, $res1['id']);
  468. return $res1;
  469. });
  470. //用户申请体现事件
  471. event('user.extract', [$user, $data, $res1]);
  472. return true;
  473. }
  474. /**
  475. * @param array $where
  476. * @param string $SumField
  477. * @param string $selectType
  478. * @param string $group
  479. * @return float|mixed
  480. */
  481. public function getOutMoneyByWhere(array $where, string $SumField, string $selectType, string $group = "")
  482. {
  483. switch ($selectType) {
  484. case "sum" :
  485. return $this->dao->getWhereSumField($where, $SumField);
  486. case "group" :
  487. return $this->dao->getGroupField($where, $SumField, $group);
  488. }
  489. }
  490. }