UserExtractServices.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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\services\BaseServices;
  14. use app\dao\user\UserExtractDao;
  15. use app\services\order\StoreOrderCreateServices;
  16. use app\services\system\admin\SystemAdminServices;
  17. use app\services\wechat\WechatUserServices;
  18. use crmeb\exceptions\AdminException;
  19. use app\jobs\RoutineTemplateJob;
  20. use app\jobs\WechatTemplateJob as TemplateJob;
  21. use crmeb\services\WechatService;
  22. use crmeb\services\workerman\ChannelService;
  23. use crmeb\services\FormBuilder as Form;
  24. use think\exception\ValidateException;
  25. use think\facade\Route as Url;
  26. /**
  27. *
  28. * Class UserExtractServices
  29. * @package app\services\user
  30. */
  31. class UserExtractServices extends BaseServices
  32. {
  33. /**
  34. * UserExtractServices constructor.
  35. * @param UserExtractDao $dao
  36. */
  37. public function __construct(UserExtractDao $dao)
  38. {
  39. $this->dao = $dao;
  40. }
  41. /**
  42. * 获取一条提现记录
  43. * @param int $id
  44. * @param array $field
  45. * @return array|\think\Model|null
  46. */
  47. public function getExtract(int $id, array $field = [])
  48. {
  49. return $this->dao->get($id, $field);
  50. }
  51. /**
  52. * 获取某个用户提现总数
  53. * @param int $uid
  54. * @return float
  55. */
  56. public function getUserExtract(int $uid)
  57. {
  58. return $this->dao->getWhereSum(['uid' => $uid, 'status' => 1]);
  59. }
  60. /**
  61. * 获取某些用户的提现总数列表
  62. * @param array $uids
  63. */
  64. public function getUsersSumList(array $uids)
  65. {
  66. return $this->dao->getWhereSumList(['uid' => $uids, 'status' => 1]);
  67. }
  68. public function getCount(array $where = [])
  69. {
  70. return $this->dao->getCount($where);
  71. }
  72. /**
  73. * 获取提现列表
  74. * @param array $where
  75. * @param string $field
  76. * @return array
  77. * @throws \think\db\exception\DataNotFoundException
  78. * @throws \think\db\exception\DbException
  79. * @throws \think\db\exception\ModelNotFoundException
  80. */
  81. public function getUserExtractList(array $where, string $field = '*')
  82. {
  83. [$page, $limit] = $this->getPageValue();
  84. $list = $this->dao->getExtractList($where, $field, $page, $limit);
  85. foreach ($list as &$item) {
  86. $item['nickname'] = $item['user']['nickname'] ?? '';
  87. }
  88. $count = $this->dao->count($where);
  89. return compact('list', 'count');
  90. }
  91. /**
  92. * 获取提现总数
  93. * @param array $where
  94. */
  95. public function getExtractSum(array $where)
  96. {
  97. return $this->dao->getExtractMoneyByWhere($where, 'extract_price');
  98. }
  99. /**
  100. * 拒绝提现申请
  101. * @param $id
  102. * @param $fail_msg
  103. * @return bool
  104. * @throws \think\db\exception\DataNotFoundException
  105. * @throws \think\db\exception\ModelNotFoundException
  106. * @throws \think\exception\DbException
  107. */
  108. public function changeFail(int $id, $userExtract, $message)
  109. {
  110. $fail_time = time();
  111. $extract_number = $userExtract['extract_price'];
  112. $mark = '提现失败,退回佣金' . $extract_number . '元';
  113. $uid = $userExtract['uid'];
  114. $status = -1;
  115. /** @var UserServices $userServices */
  116. $userServices = app()->make(UserServices::class);
  117. $user = $userServices->getUserInfo($uid);
  118. /** @var UserBillServices $userBill */
  119. $userBill = app()->make(UserBillServices::class);
  120. $bill_data = ['title' => '提现失败', 'link_id' => $userExtract['id'], 'number' => $extract_number, 'balance' => $user['now_money'], 'mark' => $mark];
  121. $this->transaction(function () use ($user, $bill_data, $userBill, $uid, $id, $extract_number, $message, $userServices, $status, $fail_time) {
  122. $userBill->incomeNowMoney($user['uid'], 'extract', $bill_data);
  123. $userServices->addBrokeragePrice($uid, $user['brokerage_price'], $extract_number);
  124. if (!$this->dao->update($id, ['fail_time' => $fail_time, 'fail_msg' => $message, 'status' => $status])) {
  125. throw new AdminException('修改失败');
  126. }
  127. });
  128. /** @var WechatUserServices $wechatServices */
  129. $wechatServices = app()->make(WechatUserServices::class);
  130. if (strtolower($user['user_type']) == 'wechat') {
  131. $openid = $wechatServices->uidToOpenid($uid, 'wechat');
  132. TemplateJob::dispatchDo('sendUserBalanceChangeFail', [$openid, $extract_number, $message]);
  133. } else if (strtolower($user['user_type']) == 'routine') {
  134. $openid = $wechatServices->uidToOpenid($uid, 'routine');
  135. RoutineTemplateJob::dispatchDo('sendExtractFail', [$openid, $message, $extract_number, $user['nickname']]);
  136. }
  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. /** @var WechatUserServices $wechatServices */
  151. $wechatServices = app()->make(WechatUserServices::class);
  152. /** @var UserServices $userServices */
  153. $userServices = app()->make(UserServices::class);
  154. $userType = $userServices->value(['uid' => $userExtract['uid']], 'user_type');
  155. if ($userType) {
  156. if (strtolower($userType) == 'routine') {
  157. $openid = $wechatServices->uidToOpenid($userExtract['uid'], 'routine');
  158. $nickname = $userServices->value(['uid' => $userExtract['uid']], 'nickname');
  159. RoutineTemplateJob::dispatchDo('sendExtractSuccess', [$openid, $extractNumber, $nickname]);
  160. } else {
  161. $openid = $wechatServices->uidToOpenid($userExtract['uid'], 'wechat');
  162. TemplateJob::dispatchDo('sendUserBalanceChangeSuccess', [$openid, $extractNumber]);
  163. }
  164. }
  165. if (!$this->dao->update($id, ['status' => 1])) {
  166. throw new AdminException('修改失败');
  167. }
  168. return true;
  169. }
  170. /**
  171. * 显示资源列表
  172. * @param array $where
  173. * @return array
  174. * @throws \think\db\exception\DataNotFoundException
  175. * @throws \think\db\exception\DbException
  176. * @throws \think\db\exception\ModelNotFoundException
  177. */
  178. public function index(array $where)
  179. {
  180. $list = $this->getUserExtractList($where);
  181. /** @var UserServices $userServices */
  182. $userServices = app()->make(UserServices::class);
  183. //待提现金额
  184. $where['status'] = 0;
  185. $extract_statistics['price'] = $this->getExtractSum($where);
  186. //已提现金额
  187. $where['status'] = 1;
  188. $extract_statistics['priced'] = $this->getExtractSum($where);
  189. //佣金总金额
  190. /** @var UserBillServices $userBillServices */
  191. $userBillServices = app()->make(UserBillServices::class);
  192. $extract_statistics['brokerage_count'] = $userBillServices->getUsersBokerageSum($where);
  193. //未提现金额
  194. $extract_statistics['brokerage_not'] = $extract_statistics['brokerage_count'] > $extract_statistics['priced'] ? bcsub((string)$extract_statistics['brokerage_count'], (string)$extract_statistics['priced'], 2) : 0.00;
  195. return compact('extract_statistics', 'list');
  196. }
  197. /**
  198. * 显示编辑资源表单页.
  199. *
  200. * @param int $id
  201. * @return \think\Response
  202. */
  203. public function edit(int $id)
  204. {
  205. $UserExtract = $this->getExtract($id);
  206. if (!$UserExtract) {
  207. throw new AdminException('数据不存在!');
  208. }
  209. $f = array();
  210. $f[] = Form::input('real_name', '姓名', $UserExtract['real_name']);
  211. $f[] = Form::number('extract_price', '提现金额', (float)$UserExtract['extract_price'])->precision(2);
  212. if ($UserExtract['extract_type'] == 'alipay') {
  213. $f[] = Form::input('alipay_code', '支付宝账号', $UserExtract['alipay_code']);
  214. } else if ($UserExtract['extract_type'] == 'weixin') {
  215. $f[] = Form::input('wechat', '微信号', $UserExtract['wechat']);
  216. } else {
  217. $f[] = Form::input('bank_code', '银行卡号', $UserExtract['bank_code']);
  218. $f[] = Form::input('bank_address', '开户行', $UserExtract['bank_address']);
  219. }
  220. $f[] = Form::input('mark', '备注', $UserExtract['mark'])->type('textarea');
  221. return create_form('编辑', $f, Url::buildUrl('/finance/extract/' . $id), 'PUT');
  222. }
  223. public function update(int $id, array $data)
  224. {
  225. if (!$this->dao->update($id, $data))
  226. throw new AdminException('修改失败');
  227. else
  228. return true;
  229. }
  230. /**
  231. * 拒绝
  232. * @param $id
  233. * @return mixed
  234. */
  235. public function refuse(int $id, string $message)
  236. {
  237. $extract = $this->getExtract($id);
  238. if (!$extract) {
  239. throw new AdminException('操作记录不存在!');
  240. }
  241. if ($extract->status == 1) {
  242. throw new AdminException('已经提现,错误操作');
  243. }
  244. if ($extract->status == -1) {
  245. throw new AdminException('您的提现申请已被拒绝,请勿重复操作!');
  246. }
  247. $res = $this->changeFail($id, $extract, $message);
  248. if ($res) {
  249. return true;
  250. } else {
  251. throw new AdminException('操作失败!');
  252. }
  253. }
  254. /**
  255. * 通过
  256. * @param $id
  257. * @return mixed
  258. */
  259. public function adopt(int $id)
  260. {
  261. $extract = $this->getExtract($id);
  262. if (!$extract) {
  263. throw new AdminException('操作记录不存!');
  264. }
  265. if ($extract->status == 1) {
  266. throw new AdminException('您已提现,请勿重复提现!');
  267. }
  268. if ($extract->status == -1) {
  269. throw new AdminException('您的提现申请已被拒绝!');
  270. }
  271. if ($this->changeSuccess($id, $extract)) {
  272. return true;
  273. } else {
  274. throw new AdminException('操作失败!');
  275. }
  276. }
  277. /**待提现的数量
  278. * @return int
  279. */
  280. public function userExtractCount()
  281. {
  282. return $this->dao->count(['status' => 0]);
  283. }
  284. /**
  285. * 银行卡提现
  286. * @param int $uid
  287. * @return mixed
  288. */
  289. public function bank(int $uid)
  290. {
  291. /** @var UserServices $userService */
  292. $userService = app()->make(UserServices::class);
  293. $user = $userService->getUserInfo($uid);
  294. if (!$user) {
  295. throw new ValidateException('数据不存在');
  296. }
  297. /** @var UserBrokerageFrozenServices $services */
  298. $services = app()->make(UserBrokerageFrozenServices::class);
  299. $data['broken_commission'] = array_bc_sum($services->getUserFrozenPrice($uid));
  300. if ($data['broken_commission'] < 0)
  301. $data['broken_commission'] = '0';
  302. $data['brokerage_price'] = $user['brokerage_price'];
  303. //可提现佣金
  304. $data['commissionCount'] = bcsub((string)$data['brokerage_price'], $data['broken_commission'], 2);
  305. $extractBank = sys_config('user_extract_bank') ?? []; //提现银行
  306. $extractBank = str_replace("\r\n", "\n", $extractBank);//防止不兼容
  307. $data['extractBank'] = explode("\n", is_array($extractBank) ? (isset($extractBank[0]) ? $extractBank[0] : $extractBank) : $extractBank);
  308. $data['minPrice'] = sys_config('user_extract_min_price');//提现最低金额
  309. return $data;
  310. }
  311. /**
  312. * 提现申请
  313. * @param int $uid
  314. * @param array $data
  315. */
  316. public function cash(int $uid, array $data)
  317. {
  318. /** @var UserServices $userService */
  319. $userService = app()->make(UserServices::class);
  320. $user = $userService->getUserInfo($uid);
  321. if (!$user) {
  322. throw new ValidateException('数据不存在');
  323. }
  324. /** @var UserBillServices $userBill */
  325. $userBill = app()->make(UserBillServices::class);
  326. /** @var UserBrokerageFrozenServices $services */
  327. $services = app()->make(UserBrokerageFrozenServices::class);
  328. $data['broken_commission'] = array_bc_sum($services->getUserFrozenPrice($uid));
  329. if ($data['broken_commission'] < 0)
  330. $data['broken_commission'] = 0;
  331. $data['brokerage_price'] = $user['brokerage_price'];
  332. //可提现佣金
  333. $commissionCount = bcsub($data['brokerage_price'], $data['broken_commission'], 2);
  334. if ($data['money'] > $commissionCount) {
  335. throw new ValidateException('可提现佣金不足');
  336. }
  337. $extractPrice = $user['brokerage_price'];
  338. $userExtractMinPrice = sys_config('user_extract_min_price');
  339. if ($data['money'] < $userExtractMinPrice) {
  340. throw new ValidateException('提现金额不能小于' . $userExtractMinPrice . '元');
  341. }
  342. if ($extractPrice < 0) {
  343. throw new ValidateException('提现佣金不足' . $data['money']);
  344. }
  345. if ($data['money'] > $extractPrice) {
  346. throw new ValidateException('提现佣金不足' . $data['money']);
  347. }
  348. if ($data['money'] <= 0) {
  349. throw new ValidateException('提现佣金大于0');
  350. }
  351. $openid = '';
  352. $insertData = [
  353. 'uid' => $user['uid'],
  354. 'extract_type' => $data['extract_type'],
  355. 'extract_price' => $data['money'],
  356. 'add_time' => time(),
  357. 'balance' => $user['brokerage_price'],
  358. 'status' => 0
  359. ];
  360. if (isset($data['name']) && strlen(trim($data['name']))) $insertData['real_name'] = $data['name'];
  361. else $insertData['real_name'] = $user['nickname'];
  362. if (isset($data['cardnum'])) $insertData['bank_code'] = $data['cardnum'];
  363. else $insertData['bank_code'] = '';
  364. if (isset($data['bankname'])) $insertData['bank_address'] = $data['bankname'];
  365. else $insertData['bank_address'] = '';
  366. if (isset($data['weixin'])) $insertData['wechat'] = $data['weixin'];
  367. else $insertData['wechat'] = $user['nickname'];
  368. if ($data['extract_type'] == 'alipay') {
  369. $insertData['alipay_code'] = $data['alipay_code'];
  370. $insertData['qrcode_url'] = $data['qrcode_url'];
  371. $mark = '使用支付宝提现' . $insertData['extract_price'] . '元';
  372. } else if ($data['extract_type'] == 'bank') {
  373. $mark = '使用银联卡' . $insertData['bank_code'] . '提现' . $insertData['extract_price'] . '元';
  374. } else if ($data['extract_type'] == 'weixin') {
  375. $insertData['qrcode_url'] = $data['qrcode_url'];
  376. $mark = '使用微信提现' . $insertData['extract_price'] . '元';
  377. /** @var WechatUserServices $wechatServices */
  378. $wechatServices = app()->make(WechatUserServices::class);
  379. $openid = $wechatServices->getWechatOpenid($uid);
  380. if (sys_config('brokerage_type', 0) && $openid) {
  381. $insertData['status'] = 1;
  382. /** @var StoreOrderCreateServices $services */
  383. $services = app()->make(StoreOrderCreateServices::class);
  384. $insertData['wechat_order_id'] = $services->getNewOrderId();
  385. if ($data['money'] < 1) {
  386. throw new ValidateException('企业微信付款到零钱最低金额为1元');
  387. }
  388. }
  389. }
  390. $res1 = $this->transaction(function () use ($insertData, $data, $uid, $userService, $user, $userBill, $mark, $openid) {
  391. if (!$res1 = $this->dao->save($insertData)) {
  392. throw new ValidateException('提现失败');
  393. }
  394. $balance = bcsub((string)$user['brokerage_price'], (string)$data['money'], 2) ?? 0;
  395. if (!$userService->update($uid, ['brokerage_price' => $balance], 'uid')) {
  396. throw new ValidateException('修改用户信息失败');
  397. }
  398. $bill_data = ['title' => '佣金提现', 'link_id' => $res1['id'], 'balance' => $user['brokerage_price'], 'number' => $data['money'], 'mark' => $mark];
  399. if (!$userBill->expendNowMoney($uid, 'extract', $bill_data)) {
  400. throw new ValidateException('保存佣金提现记录失败');
  401. }
  402. //自动提现到零钱
  403. if ($insertData['extract_type'] == 'weixin' && $insertData['status'] == 1 && isset($insertData['wechat_order_id'])) {
  404. $res = WechatService::merchantPay($openid, $insertData['wechat_order_id'], $data['money'], '提现佣金到零钱');
  405. if (!$res) {
  406. throw new ValidateException('企业付款到零钱失败,请稍后再试');
  407. }
  408. }
  409. return $res1;
  410. });
  411. try {
  412. ChannelService::instance()->send('WITHDRAW', ['id' => $res1->id]);
  413. } catch (\Exception $e) {
  414. }
  415. /** @var SystemAdminServices $systemAdmin */
  416. $systemAdmin = app()->make(SystemAdminServices::class);
  417. $systemAdmin->adminNewPush();
  418. //发送模板消息
  419. return true;
  420. }
  421. /**
  422. * @param array $where
  423. * @param string $SumField
  424. * @param string $selectType
  425. * @param string $group
  426. * @return float|mixed
  427. */
  428. public function getOutMoneyByWhere(array $where, string $SumField, string $selectType, string $group = "")
  429. {
  430. switch ($selectType) {
  431. case "sum" :
  432. return $this->dao->getWhereSumField($where, $SumField);
  433. case "group" :
  434. return $this->dao->getGroupField($where, $SumField, $group);
  435. }
  436. }
  437. }