UserExtractServices.php 22 KB

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