UserRechargeServices.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2023 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\dao\user\UserRechargeDao;
  14. use app\services\BaseServices;
  15. use app\services\order\StoreOrderCreateServices;
  16. use app\services\pay\PayServices;
  17. use app\services\pay\RechargeServices;
  18. use app\services\statistic\CapitalFlowServices;
  19. use app\services\system\config\SystemGroupDataServices;
  20. use app\services\wechat\WechatUserServices;
  21. use crmeb\exceptions\AdminException;
  22. use crmeb\exceptions\ApiException;
  23. use crmeb\services\FormBuilder as Form;
  24. use crmeb\services\pay\Pay;
  25. use think\facade\Route as Url;
  26. /**
  27. *
  28. * Class UserRechargeServices
  29. * @package app\services\user
  30. * @method be($map, string $field = '') 查询一条数据是否存在
  31. * @method getDistinctCount(array $where, $field, ?bool $search = true)
  32. * @method getTrendData($time, $type, $timeType)
  33. */
  34. class UserRechargeServices extends BaseServices
  35. {
  36. /**
  37. * UserRechargeServices constructor.
  38. * @param UserRechargeDao $dao
  39. */
  40. public function __construct(UserRechargeDao $dao)
  41. {
  42. $this->dao = $dao;
  43. }
  44. /**
  45. * 获取单条数据
  46. * @param int $id
  47. * @param array $field
  48. */
  49. public function getRecharge(int $id, array $field = [])
  50. {
  51. return $this->dao->get($id, $field);
  52. }
  53. /**
  54. * 获取统计数据
  55. * @param array $where
  56. * @param string $field
  57. * @return float
  58. */
  59. public function getRechargeSum(array $where, string $field = '')
  60. {
  61. $whereData = [];
  62. if (isset($where['data'])) {
  63. $whereData['time'] = $where['data'];
  64. }
  65. if (isset($where['paid']) && $where['paid'] != '') {
  66. $whereData['paid'] = $where['paid'];
  67. }
  68. if (isset($where['nickname']) && $where['nickname']) {
  69. $whereData['like'] = $where['nickname'];
  70. }
  71. if (isset($where['recharge_type']) && $where['recharge_type']) {
  72. $whereData['recharge_type'] = $where['recharge_type'];
  73. }
  74. return $this->dao->getWhereSumField($whereData, $field);
  75. }
  76. /**
  77. * 获取充值列表
  78. * @param array $where
  79. * @param string $field
  80. * @return array
  81. */
  82. public function getRechargeList(array $where, string $field = '*', $is_page = true)
  83. {
  84. $whereData = [];
  85. if (isset($where['data'])) {
  86. $whereData['time'] = $where['data'];
  87. }
  88. if (isset($where['paid']) && $where['paid'] != '') {
  89. $whereData['paid'] = $where['paid'];
  90. }
  91. if (isset($where['nickname']) && $where['nickname']) {
  92. $whereData['like'] = $where['nickname'];
  93. }
  94. [$page, $limit] = $this->getPageValue($is_page);
  95. $list = $this->dao->getList($whereData, $field, $page, $limit);
  96. $count = $this->dao->count($whereData);
  97. foreach ($list as &$item) {
  98. switch ($item['recharge_type']) {
  99. case PayServices::WEIXIN_PAY:
  100. $item['_recharge_type'] = '微信充值';
  101. break;
  102. case 'system':
  103. $item['_recharge_type'] = '系统充值';
  104. break;
  105. case PayServices::ALIAPY_PAY:
  106. $item['_recharge_type'] = '支付宝充值';
  107. break;
  108. default:
  109. $item['_recharge_type'] = '其他充值';
  110. break;
  111. }
  112. $item['_pay_time'] = $item['pay_time'] ? date('Y-m-d H:i:s', $item['pay_time']) : '暂无';
  113. $item['_add_time'] = $item['add_time'] ? date('Y-m-d H:i:s', $item['add_time']) : '暂无';
  114. $item['paid_type'] = $item['paid'] ? '已支付' : '未支付';
  115. $item['avatar'] = strpos($item['avatar'] ?? '', 'http') === false ? (sys_config('site_url') . $item['avatar']) : $item['avatar'];
  116. unset($item['user']);
  117. }
  118. return compact('list', 'count');
  119. }
  120. /**
  121. * 获取用户充值数据
  122. * @return array
  123. */
  124. public function user_recharge(array $where)
  125. {
  126. $data = [];
  127. $data['sumPrice'] = $this->getRechargeSum($where, 'price');
  128. $data['sumRefundPrice'] = $this->getRechargeSum($where, 'refund_price');
  129. $where['recharge_type'] = 'alipay';
  130. $data['sumAlipayPrice'] = $this->getRechargeSum($where, 'price');
  131. $where['recharge_type'] = 'weixin';
  132. $data['sumWeixinPrice'] = $this->getRechargeSum($where, 'price');
  133. return [
  134. [
  135. 'name' => '充值总金额',
  136. 'field' => '元',
  137. 'count' => $data['sumPrice'],
  138. 'className' => 'logo-yen',
  139. 'col' => 6,
  140. ],
  141. [
  142. 'name' => '充值退款金额',
  143. 'field' => '元',
  144. 'count' => $data['sumRefundPrice'],
  145. 'className' => 'logo-usd',
  146. 'col' => 6,
  147. ],
  148. [
  149. 'name' => '支付宝充值金额',
  150. 'field' => '元',
  151. 'count' => $data['sumAlipayPrice'],
  152. 'className' => 'logo-bitcoin',
  153. 'col' => 6,
  154. ],
  155. [
  156. 'name' => '微信充值金额',
  157. 'field' => '元',
  158. 'count' => $data['sumWeixinPrice'],
  159. 'className' => 'ios-bicycle',
  160. 'col' => 6,
  161. ],
  162. ];
  163. }
  164. /**
  165. * 退款表单
  166. * @param int $id
  167. * @return array
  168. * @throws \FormBuilder\Exception\FormBuilderException
  169. * @author 吴汐
  170. * @email 442384644@qq.com
  171. * @date 2023/03/24
  172. */
  173. public function refund_edit(int $id)
  174. {
  175. $UserRecharge = $this->getRecharge($id);
  176. if (!$UserRecharge) {
  177. throw new AdminException(100026);
  178. }
  179. if ($UserRecharge['paid'] != 1) {
  180. throw new AdminException(400677);
  181. }
  182. if ($UserRecharge['price'] == $UserRecharge['refund_price']) {
  183. throw new AdminException(400147);
  184. }
  185. if ($UserRecharge['recharge_type'] == 'balance') {
  186. throw new AdminException(400678);
  187. }
  188. $f = array();
  189. $f[] = Form::input('order_id', '退款单号', $UserRecharge->getData('order_id'))->disabled(true);
  190. $f[] = Form::radio('refund_price', '状态', 1)->options([['label' => '本金(扣赠送余额)', 'value' => 1], ['label' => '仅本金', 'value' => 0]]);
  191. return create_form('编辑', $f, Url::buildUrl('/finance/recharge/' . $id), 'PUT');
  192. }
  193. /**
  194. * 退款操作
  195. * @param int $id
  196. * @param string $refund_price
  197. * @return mixed
  198. * @throws \think\db\exception\DataNotFoundException
  199. * @throws \think\db\exception\DbException
  200. * @throws \think\db\exception\ModelNotFoundException
  201. */
  202. public function refund_update(int $id, string $refund_price)
  203. {
  204. $UserRecharge = $this->getRecharge($id);
  205. if (!$UserRecharge) {
  206. throw new AdminException(100026);
  207. }
  208. if ($UserRecharge['price'] == $UserRecharge['refund_price']) {
  209. throw new AdminException(400147);
  210. }
  211. if ($UserRecharge['recharge_type'] == 'balance') {
  212. throw new AdminException(400678);
  213. }
  214. $data['refund_price'] = $UserRecharge['price'];
  215. $refund_data['pay_price'] = $UserRecharge['price'];
  216. $refund_data['refund_price'] = $UserRecharge['price'];
  217. if ($refund_price == 1) {
  218. $number = bcadd($UserRecharge['price'], $UserRecharge['give_price'], 2);
  219. } else {
  220. $number = $UserRecharge['price'];
  221. }
  222. try {
  223. $recharge_type = $UserRecharge['recharge_type'];
  224. /** @var Pay $pay */
  225. $pay = app()->make(Pay::class);
  226. if ($recharge_type == 'weixin') {
  227. $refund_data['wechat'] = true;
  228. $pay->refund($UserRecharge['order_id'], $refund_data);
  229. } else {
  230. $refund_data['trade_no'] = $UserRecharge['trade_no'];
  231. $refund_data['order_id'] = $UserRecharge['order_id'];
  232. /** @var WechatUserServices $wechatUserServices */
  233. $wechatUserServices = app()->make(WechatUserServices::class);
  234. $refund_data['open_id'] = $wechatUserServices->uidToOpenid((int)$UserRecharge['uid'], 'routine') ?? '';
  235. $refund_data['pay_new_weixin_open'] = sys_config('pay_new_weixin_open');
  236. /** @var StoreOrderCreateServices $storeOrderCreateServices */
  237. $storeOrderCreateServices = app()->make(StoreOrderCreateServices::class);
  238. $refund_data['refund_no'] = $storeOrderCreateServices->getNewOrderId('tk');
  239. $pay->refund($UserRecharge['order_id'], $refund_data);
  240. }
  241. } catch (\Exception $e) {
  242. throw new AdminException($e->getMessage());
  243. }
  244. if (!$this->dao->update($id, $data)) {
  245. throw new AdminException(100007);
  246. }
  247. //修改用户余额
  248. /** @var UserServices $userServices */
  249. $userServices = app()->make(UserServices::class);
  250. $userInfo = $userServices->getUserInfo($UserRecharge['uid']);
  251. if ($userInfo['now_money'] > $number) {
  252. $now_money = bcsub((string)$userInfo['now_money'], $number, 2);
  253. } else {
  254. $number = $userInfo['now_money'];
  255. $now_money = 0;
  256. }
  257. $userServices->update((int)$UserRecharge['uid'], ['now_money' => $now_money], 'uid');
  258. //写入资金流水
  259. /** @var CapitalFlowServices $capitalFlowServices */
  260. $capitalFlowServices = app()->make(CapitalFlowServices::class);
  261. $UserRecharge['nickname'] = $userInfo['nickname'];
  262. $UserRecharge['phone'] = $userInfo['phone'];
  263. $capitalFlowServices->setFlow($UserRecharge, 'refund_recharge');
  264. //保存余额记录
  265. /** @var UserMoneyServices $userMoneyServices */
  266. $userMoneyServices = app()->make(UserMoneyServices::class);
  267. $userMoneyServices->income('user_recharge_refund', $UserRecharge['uid'], $number, $now_money, $id);
  268. //提醒推送
  269. event('NoticeListener', [['user_type' => strtolower($userInfo['user_type']), 'data' => $data, 'UserRecharge' => $UserRecharge, 'now_money' => $refund_price], 'recharge_order_refund_status']);
  270. return true;
  271. }
  272. /**
  273. * 删除
  274. * @param int $id
  275. * @return bool
  276. */
  277. public function delRecharge(int $id)
  278. {
  279. $rechargInfo = $this->getRecharge($id);
  280. if (!$rechargInfo) throw new AdminException(100026);
  281. if ($rechargInfo->paid) {
  282. throw new AdminException(400679);
  283. }
  284. if ($this->dao->delete($id))
  285. return true;
  286. else
  287. throw new AdminException(100008);
  288. }
  289. /**
  290. * 生成充值订单号
  291. * @return bool|string
  292. */
  293. public function getOrderId()
  294. {
  295. return 'wx' . date('YmdHis', time()) . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
  296. }
  297. /**
  298. * 导入佣金到余额
  299. * @param int $uid
  300. * @param $price
  301. * @return bool
  302. * @throws \think\db\exception\DataNotFoundException
  303. * @throws \think\db\exception\DbException
  304. * @throws \think\db\exception\ModelNotFoundException
  305. */
  306. public function importNowMoney(int $uid, $price)
  307. {
  308. /** @var UserServices $userServices */
  309. $userServices = app()->make(UserServices::class);
  310. $user = $userServices->getUserInfo($uid);
  311. if (!$user) {
  312. throw new ApiException(100100);
  313. }
  314. /** @var UserBrokerageServices $frozenPrices */
  315. $frozenPrices = app()->make(UserBrokerageServices::class);
  316. $broken_commission = $frozenPrices->getUserFrozenPrice($uid);
  317. $commissionCount = bcsub((string)$user['brokerage_price'], (string)$broken_commission, 2);
  318. if ($price > $commissionCount) {
  319. throw new ApiException(400680);
  320. }
  321. $edit_data = [];
  322. $edit_data['now_money'] = bcadd((string)$user['now_money'], (string)$price, 2);
  323. $edit_data['brokerage_price'] = $user['brokerage_price'] > $price ? bcsub((string)$user['brokerage_price'], (string)$price, 2) : 0;
  324. if (!$userServices->update($uid, $edit_data, 'uid')) {
  325. throw new ApiException(100007);
  326. }
  327. //写入充值记录
  328. $rechargeInfo = [
  329. 'uid' => $uid,
  330. 'order_id' => app()->make(StoreOrderCreateServices::class)->getNewOrderId('cz'),
  331. 'recharge_type' => 'balance',
  332. 'price' => $price,
  333. 'give_price' => 0,
  334. 'paid' => 1,
  335. 'pay_time' => time(),
  336. 'add_time' => time()
  337. ];
  338. if (!$re = $this->dao->save($rechargeInfo)) {
  339. throw new ApiException(400681);
  340. }
  341. //余额记录
  342. /** @var UserMoneyServices $userMoneyServices */
  343. $userMoneyServices = app()->make(UserMoneyServices::class);
  344. $userMoneyServices->income('brokerage_to_nowMoney', $uid, $price, $edit_data['now_money'], $re['id']);
  345. //写入提现记录
  346. $extractInfo = [
  347. 'uid' => $uid,
  348. 'real_name' => $user['nickname'],
  349. 'extract_type' => 'balance',
  350. 'extract_price' => $price,
  351. 'balance' => $user['brokerage_price'],
  352. 'add_time' => time(),
  353. 'status' => 1
  354. ];
  355. /** @var UserExtractServices $userExtract */
  356. $userExtract = app()->make(UserExtractServices::class);
  357. $userExtract->save($extractInfo);
  358. //佣金提现记录
  359. /** @var UserBrokerageServices $userBrokerageServices */
  360. $userBrokerageServices = app()->make(UserBrokerageServices::class);
  361. $userBrokerageServices->income('brokerage_to_nowMoney', $uid, $price, $edit_data['brokerage_price'], $re['id']);
  362. return true;
  363. }
  364. /**
  365. * 申请充值
  366. * @param int $uid
  367. * @param $price
  368. * @param $recharId
  369. * @param $type
  370. * @param $from
  371. * @param bool $renten
  372. * @return mixed
  373. * @throws \think\db\exception\DataNotFoundException
  374. * @throws \think\db\exception\DbException
  375. * @throws \think\db\exception\ModelNotFoundException
  376. */
  377. public function recharge(int $uid, $price, $recharId, $type, $from, bool $renten = false)
  378. {
  379. /** @var UserServices $userServices */
  380. $userServices = app()->make(UserServices::class);
  381. $user = $userServices->getUserInfo($uid);
  382. if (!$user) {
  383. throw new ApiException(400214);
  384. }
  385. switch ((int)$type) {
  386. case 0: //支付充值余额
  387. $paid_price = 0;
  388. if ($recharId) {
  389. /** @var SystemGroupDataServices $systemGroupData */
  390. $systemGroupData = app()->make(SystemGroupDataServices::class);
  391. $data = $systemGroupData->getDateValue($recharId);
  392. if ($data === false) {
  393. throw new ApiException(400682);
  394. } else {
  395. $paid_price = $data['give_money'] ?? 0;
  396. $price = $data['price'] ?? 0;
  397. }
  398. }
  399. $recharge_data = [];
  400. $recharge_data['order_id'] = app()->make(StoreOrderCreateServices::class)->getNewOrderId('cz');
  401. $recharge_data['uid'] = $uid;
  402. $recharge_data['price'] = $price;
  403. $recharge_data['recharge_type'] = $from;
  404. $recharge_data['paid'] = 0;
  405. $recharge_data['add_time'] = time();
  406. $recharge_data['give_price'] = $paid_price;
  407. $recharge_data['channel_type'] = $user['user_type'];
  408. if (!$rechargeOrder = $this->dao->save($recharge_data)) {
  409. throw new ApiException(400683);
  410. }
  411. try {
  412. /** @var RechargeServices $recharge */
  413. $recharge = app()->make(RechargeServices::class);
  414. $order_info = $recharge->recharge($rechargeOrder);
  415. } catch (\Exception $e) {
  416. throw new ApiException($e->getMessage());
  417. }
  418. if ($renten) {
  419. return $order_info;
  420. }
  421. return ['msg' => '', 'type' => $from, 'data' => $order_info];
  422. case 1: //佣金转入余额
  423. $this->importNowMoney($uid, $price);
  424. return ['msg' => '转入余额成功', 'type' => $from, 'data' => []];
  425. default:
  426. throw new ApiException(100100);
  427. }
  428. }
  429. /**
  430. * 用户充值成功后
  431. * @param $orderId
  432. * @param array $other
  433. * @return bool
  434. * @throws \think\db\exception\DataNotFoundException
  435. * @throws \think\db\exception\DbException
  436. * @throws \think\db\exception\ModelNotFoundException
  437. */
  438. public function rechargeSuccess($orderId, array $other = [])
  439. {
  440. $order = $this->dao->getOne(['order_id' => $orderId, 'paid' => 0]);
  441. if (!$order) {
  442. throw new ApiException(410173);
  443. }
  444. /** @var UserServices $userServices */
  445. $userServices = app()->make(UserServices::class);
  446. $user = $userServices->getUserInfo((int)$order['uid']);
  447. if (!$user) {
  448. throw new ApiException(410032);
  449. }
  450. $price = bcadd((string)$order['price'], (string)$order['give_price'], 2);
  451. if (!$this->dao->update($order['id'], ['paid' => 1, 'recharge_type' => $other['pay_type'], 'pay_time' => time(), 'trade_no' => $other['trade_no'] ?? ''], 'id')) {
  452. throw new ApiException(410286);
  453. }
  454. $now_money = bcadd((string)$user['now_money'], (string)$price, 2);
  455. /** @var UserMoneyServices $userMoneyServices */
  456. $userMoneyServices = app()->make(UserMoneyServices::class);
  457. $userMoneyServices->income('user_recharge', $user['uid'], ['number' => $price, 'price' => $order['price'], 'give_price' => $order['give_price']], $now_money, $order['id']);
  458. if (!$userServices->update((int)$order['uid'], ['now_money' => $now_money], 'uid')) {
  459. throw new ApiException(410287);
  460. }
  461. /** @var CapitalFlowServices $capitalFlowServices */
  462. $capitalFlowServices = app()->make(CapitalFlowServices::class);
  463. $order['nickname'] = $user['nickname'];
  464. $order['phone'] = $user['phone'];
  465. $capitalFlowServices->setFlow($order, 'recharge');
  466. // 小程序订单服务
  467. event('OrderShipping', ['recharge', $order]);
  468. //提醒推送
  469. event('NoticeListener', [['order' => $order, 'now_money' => $now_money], 'recharge_success']);
  470. return true;
  471. }
  472. /**
  473. * 根据查询用户充值金额
  474. * @param array $where
  475. * @param string $rechargeSumField
  476. * @param string $selectType
  477. * @param string $group
  478. * @return float|int
  479. */
  480. public function getRechargeMoneyByWhere(array $where, string $rechargeSumField, string $selectType, string $group = "")
  481. {
  482. switch ($selectType) {
  483. case "sum" :
  484. return $this->dao->getWhereSumField($where, $rechargeSumField);
  485. case "group" :
  486. return $this->dao->getGroupField($where, $rechargeSumField, $group);
  487. }
  488. }
  489. }