UserRechargeServices.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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\dao\user\UserRechargeDao;
  14. use app\services\BaseServices;
  15. use app\services\pay\RechargeServices;
  16. use app\services\system\config\SystemGroupDataServices;
  17. use crmeb\exceptions\AdminException;
  18. use crmeb\services\{
  19. FormBuilder as Form, MiniProgramService, WechatService
  20. };
  21. use think\exception\ValidateException;
  22. use think\facade\Route as Url;
  23. /**
  24. *
  25. * Class UserRechargeServices
  26. * @package app\services\user
  27. * @method be($map, string $field = '') 查询一条数据是否存在
  28. * @method getDistinctCount(array $where, $field, ?bool $search = true)
  29. * @method getTrendData($time, $type, $timeType)
  30. */
  31. class UserRechargeServices extends BaseServices
  32. {
  33. /**
  34. * UserRechargeServices constructor.
  35. * @param UserRechargeDao $dao
  36. */
  37. public function __construct(UserRechargeDao $dao)
  38. {
  39. $this->dao = $dao;
  40. }
  41. /**
  42. * 获取单条数据
  43. * @param int $id
  44. * @param array $field
  45. */
  46. public function getRecharge(int $id, array $field = [])
  47. {
  48. return $this->dao->get($id, $field);
  49. }
  50. /**
  51. * 获取统计数据
  52. * @param array $where
  53. * @param string $field
  54. * @return float
  55. */
  56. public function getRechargeSum(array $where, string $field = '')
  57. {
  58. $whereData = [];
  59. if (isset($where['data'])) {
  60. $whereData['time'] = $where['data'];
  61. }
  62. if (isset($where['paid']) && $where['paid'] != '') {
  63. $whereData['paid'] = $where['paid'];
  64. }
  65. if (isset($where['nickname']) && $where['nickname']) {
  66. $whereData['like'] = $where['nickname'];
  67. }
  68. if (isset($where['recharge_type']) && $where['recharge_type']) {
  69. $whereData['recharge_type'] = $where['recharge_type'];
  70. }
  71. return $this->dao->getWhereSumField($whereData, $field);
  72. }
  73. /**
  74. * 获取充值列表
  75. * @param array $where
  76. * @param string $field
  77. * @return array
  78. */
  79. public function getRechargeList(array $where, string $field = '*', $is_page = true)
  80. {
  81. $whereData = [];
  82. if (isset($where['data'])) {
  83. $whereData['time'] = $where['data'];
  84. }
  85. if (isset($where['paid']) && $where['paid'] != '') {
  86. $whereData['paid'] = $where['paid'];
  87. }
  88. if (isset($where['nickname']) && $where['nickname']) {
  89. $whereData['like'] = $where['nickname'];
  90. }
  91. [$page, $limit] = $this->getPageValue($is_page);
  92. $list = $this->dao->getList($whereData, $field, $page, $limit);
  93. $count = $this->dao->count($whereData);
  94. foreach ($list as &$item) {
  95. switch ($item['recharge_type']) {
  96. case 'routine':
  97. $item['_recharge_type'] = '小程序充值';
  98. break;
  99. case 'weixin':
  100. $item['_recharge_type'] = '公众号充值';
  101. break;
  102. default:
  103. $item['_recharge_type'] = '其他充值';
  104. break;
  105. }
  106. $item['_pay_time'] = $item['pay_time'] ? date('Y-m-d H:i:s', $item['pay_time']) : '暂无';
  107. $item['_add_time'] = $item['add_time'] ? date('Y-m-d H:i:s', $item['add_time']) : '暂无';
  108. $item['paid_type'] = $item['paid'] ? '已支付' : '未支付';
  109. unset($item['user']);
  110. }
  111. return compact('list', 'count');
  112. }
  113. /**
  114. * 获取用户充值数据
  115. * @return array
  116. */
  117. public function user_recharge(array $where)
  118. {
  119. $data = [];
  120. $data['sumPrice'] = $this->getRechargeSum($where, 'price');
  121. $data['sumRefundPrice'] = $this->getRechargeSum($where, 'refund_price');
  122. $where['recharge_type'] = 'routine';
  123. $data['sumRoutinePrice'] = $this->getRechargeSum($where, 'price');
  124. $where['recharge_type'] = 'weixin';
  125. $data['sumWeixinPrice'] = $this->getRechargeSum($where, 'price');
  126. return [
  127. [
  128. 'name' => '充值总金额',
  129. 'field' => '元',
  130. 'count' => $data['sumPrice'],
  131. 'className' => 'logo-yen',
  132. 'col' => 6,
  133. ],
  134. [
  135. 'name' => '充值退款金额',
  136. 'field' => '元',
  137. 'count' => $data['sumRefundPrice'],
  138. 'className' => 'logo-usd',
  139. 'col' => 6,
  140. ],
  141. [
  142. 'name' => '小程序充值金额',
  143. 'field' => '元',
  144. 'count' => $data['sumRoutinePrice'],
  145. 'className' => 'logo-bitcoin',
  146. 'col' => 6,
  147. ],
  148. [
  149. 'name' => '公众号充值金额',
  150. 'field' => '元',
  151. 'count' => $data['sumWeixinPrice'],
  152. 'className' => 'ios-bicycle',
  153. 'col' => 6,
  154. ],
  155. ];
  156. }
  157. /**退款表单
  158. * @param $id
  159. * @return mixed|void
  160. */
  161. public function refund_edit(int $id)
  162. {
  163. $UserRecharge = $this->getRecharge($id);
  164. if (!$UserRecharge) {
  165. throw new AdminException('数据不存在!');
  166. }
  167. if ($UserRecharge['paid'] != 1) {
  168. throw new AdminException('订单未支付');
  169. }
  170. if ($UserRecharge['price'] == $UserRecharge['refund_price']) {
  171. throw new AdminException('已退完支付金额!不能再退款了');
  172. }
  173. if ($UserRecharge['recharge_type'] == 'balance') {
  174. throw new AdminException('佣金转入余额,不能退款');
  175. }
  176. $f = array();
  177. $f[] = Form::input('order_id', '退款单号', $UserRecharge->getData('order_id'))->disabled(true);
  178. $f[] = Form::radio('refund_price', '状态', 1)->options([['label' => '本金(扣赠送余额)', 'value' => 1], ['label' => '仅本金', 'value' => 0]]);
  179. // $f[] = Form::number('refund_price', '退款金额', (float)$UserRecharge->getData('price'))->precision(2)->min(0)->max($UserRecharge->getData('price'));
  180. return create_form('编辑', $f, Url::buildUrl('/finance/recharge/' . $id), 'PUT');
  181. }
  182. /**
  183. * 退款操作
  184. * @param int $id
  185. * @param $refund_price
  186. * @return mixed
  187. */
  188. public function refund_update(int $id, string $refund_price)
  189. {
  190. $UserRecharge = $this->getRecharge($id);
  191. if (!$UserRecharge) {
  192. throw new AdminException('数据不存在!');
  193. }
  194. if ($UserRecharge['price'] == $UserRecharge['refund_price']) {
  195. throw new AdminException('已退完支付金额!不能再退款了');
  196. }
  197. if ($UserRecharge['recharge_type'] == 'balance') {
  198. throw new AdminException('佣金转入余额,不能退款');
  199. }
  200. // $data['refund_price'] = bcadd($refund_price, $UserRecharge['refund_price'], 2);
  201. $data['refund_price'] = $UserRecharge['price'];
  202. // $bj = bccomp((string)$UserRecharge['price'], (string)$data['refund_price'], 2);
  203. // if ($bj < 0) {
  204. // throw new AdminException('退款金额大于支付金额,请修改退款金额');
  205. // }
  206. $refund_data['pay_price'] = $UserRecharge['price'];
  207. $refund_data['refund_price'] = $UserRecharge['price'];
  208. // $refund_data['refund_account']='REFUND_SOURCE_RECHARGE_FUNDS';
  209. if ($refund_price == 1) {
  210. $number = bcadd($UserRecharge['price'], $UserRecharge['give_price'], 2);
  211. } else {
  212. $number = $UserRecharge['price'];
  213. }
  214. try {
  215. $recharge_type = $UserRecharge['recharge_type'];
  216. if ($recharge_type == 'weixin') {
  217. WechatService::payOrderRefund($UserRecharge['order_id'], $refund_data);
  218. } else {
  219. MiniProgramService::payOrderRefund($UserRecharge['order_id'], $refund_data);
  220. }
  221. } catch (\Exception $e) {
  222. throw new AdminException($e->getMessage());
  223. }
  224. if (!$this->dao->update($id, $data)) {
  225. throw new AdminException('修改提现数据失败');
  226. }
  227. /** @var UserServices $userServices */
  228. $userServices = app()->make(UserServices::class);
  229. $userInfo = $userServices->getUserInfo($UserRecharge['uid']);
  230. $userServices->cutNowMoney($UserRecharge['uid'], $userInfo['now_money'], $number);
  231. //提醒推送
  232. event('notice.notice', [['user_type' => strtolower($UserRecharge['recharge_type']), 'data' => $data, 'UserRecharge' => $UserRecharge, 'now_money' => $refund_price], 'recharge_order_refund_status']);
  233. $billData = ['title' => '系统退款', 'number' => $number, 'link_id' => $id, 'balance' => $userInfo['now_money'], 'mark' => '退款给用户' . $UserRecharge['price'] . '元'];
  234. /** @var UserBillServices $userBillService */
  235. $userBillService = app()->make(UserBillServices::class);
  236. $userBillService->expendNowMoney($UserRecharge['uid'], 'user_recharge_refund', $billData);
  237. return true;
  238. }
  239. /**
  240. * 删除
  241. * @param int $id
  242. * @return bool
  243. */
  244. public function delRecharge(int $id)
  245. {
  246. $rechargInfo = $this->getRecharge($id);
  247. if (!$rechargInfo) throw new AdminException('订单未找到');
  248. if ($rechargInfo->paid) {
  249. throw new AdminException('已支付的订单记录无法删除');
  250. }
  251. if ($this->dao->delete($id))
  252. return true;
  253. else
  254. throw new AdminException('删除失败');
  255. }
  256. /**
  257. * 生成充值订单号
  258. * @return bool|string
  259. */
  260. public function getOrderId()
  261. {
  262. return 'wx' . date('YmdHis', time()) . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
  263. }
  264. /**
  265. * 导入佣金到余额
  266. * @param int $uid
  267. * @param $price
  268. * @return bool
  269. */
  270. public function importNowMoney(int $uid, $price)
  271. {
  272. /** @var UserServices $userServices */
  273. $userServices = app()->make(UserServices::class);
  274. $user = $userServices->getUserInfo($uid);
  275. if (!$user) {
  276. throw new ValidateException('数据不存在');
  277. }
  278. /** @var UserBrokerageFrozenServices $frozenPrices */
  279. $frozenPrices = app()->make(UserBrokerageFrozenServices::class);
  280. $broken_commission = array_bc_sum($frozenPrices->getUserFrozenPrice($uid));
  281. $commissionCount = bcsub($user['brokerage_price'], $broken_commission, 2);
  282. if ($price > $commissionCount) {
  283. throw new ValidateException('转入金额不能大于可提现佣金!');
  284. }
  285. $edit_data = [];
  286. $edit_data['now_money'] = bcadd((string)$user['now_money'], (string)$price, 2);
  287. $edit_data['brokerage_price'] = $user['brokerage_price'] > $price ? bcsub((string)$user['brokerage_price'], (string)$price, 2) : 0;
  288. if (!$userServices->update($uid, $edit_data, 'uid')) {
  289. throw new ValidateException('修改用户信息失败');
  290. }
  291. //写入充值记录
  292. $rechargeInfo = [
  293. 'uid' => $uid,
  294. 'order_id' => $this->getOrderId(),
  295. 'recharge_type' => 'balance',
  296. 'price' => $price,
  297. 'give_price' => 0,
  298. 'paid' => 1,
  299. 'pay_time' => time(),
  300. 'add_time' => time()
  301. ];
  302. if (!$re = $this->dao->save($rechargeInfo)) {
  303. throw new ValidateException('写入余额充值失败');
  304. }
  305. $bill_data = ['title' => '用户佣金转入余额', 'link_id' => $re['id'], 'number' => $price, 'balance' => $user['now_money'], 'mark' => '成功转入余额' . floatval($price) . '元'];
  306. /** @var UserBillServices $userBill */
  307. $userBill = app()->make(UserBillServices::class);
  308. //余额充值
  309. $userBill->incomeNowMoney($uid, 'recharge', $bill_data);
  310. //写入提现记录
  311. $extractInfo = [
  312. 'uid' => $uid,
  313. 'real_name' => $user['nickname'],
  314. 'extract_type' => 'balance',
  315. 'extract_price' => $price,
  316. 'balance' => $user['brokerage_price'],
  317. 'add_time' => time(),
  318. 'status' => 1
  319. ];
  320. /** @var UserExtractServices $userExtract */
  321. $userExtract = app()->make(UserExtractServices::class);
  322. if (!$re = $userExtract->save($extractInfo)) {
  323. throw new ValidateException('写入佣金提现失败');
  324. }
  325. //佣金提现
  326. $userBill->income('brokerage_to_nowMoney', $uid, $price, $user['brokerage_price'], $re['id']);
  327. return true;
  328. }
  329. /**
  330. * 申请充值
  331. * @param int $uid
  332. * @return mixed
  333. */
  334. public function recharge(int $uid, $price, $recharId, $type, $from)
  335. {
  336. /** @var UserServices $userServices */
  337. $userServices = app()->make(UserServices::class);
  338. $user = $userServices->getUserInfo($uid);
  339. if (!$user) {
  340. throw new ValidateException('数据不存在');
  341. }
  342. switch ((int)$type) {
  343. case 0: //支付充值余额
  344. $paid_price = 0;
  345. if ($recharId) {
  346. /** @var SystemGroupDataServices $systemGroupData */
  347. $systemGroupData = app()->make(SystemGroupDataServices::class);
  348. $data = $systemGroupData->getDateValue($recharId);
  349. if ($data === false) {
  350. return app('json')->fail('您选择的充值方式已下架!');
  351. } else {
  352. $paid_price = $data['give_money'] ?? 0;
  353. }
  354. }
  355. $recharge_data = [];
  356. $recharge_data['order_id'] = $this->getOrderId();
  357. $recharge_data['uid'] = $uid;
  358. $recharge_data['price'] = $price;
  359. $recharge_data['recharge_type'] = $from;
  360. $recharge_data['paid'] = 0;
  361. $recharge_data['add_time'] = time();
  362. $recharge_data['give_price'] = $paid_price;
  363. $recharge_data['channel_type'] = $user['user_type'];
  364. if (!$rechargeOrder = $this->dao->save($recharge_data)) {
  365. throw new ValidateException('充值订单生成失败');
  366. }
  367. try {
  368. /** @var RechargeServices $recharge */
  369. $recharge = app()->make(RechargeServices::class);
  370. $order_info = $recharge->recharge((int)$rechargeOrder->id);
  371. } catch (\Exception $e) {
  372. throw new ValidateException($e->getMessage());
  373. }
  374. return ['msg' => '', 'type' => $from, 'data' => $order_info];
  375. break;
  376. case 1: //佣金转入余额
  377. $this->importNowMoney($uid, $price);
  378. return ['msg' => '转入余额成功', 'type' => $from, 'data' => []];
  379. break;
  380. default:
  381. throw new ValidateException('缺少参数');
  382. break;
  383. }
  384. }
  385. /**
  386. * //TODO用户充值成功后
  387. * @param $orderId
  388. */
  389. public function rechargeSuccess($orderId)
  390. {
  391. $order = $this->dao->getOne(['order_id' => $orderId, 'paid' => 0]);
  392. if (!$order) {
  393. throw new ValidateException('订单失效或者不存在');
  394. }
  395. /** @var UserServices $userServices */
  396. $userServices = app()->make(UserServices::class);
  397. $user = $userServices->getUserInfo((int)$order['uid']);
  398. if (!$user) {
  399. throw new ValidateException('数据不存在');
  400. }
  401. $price = bcadd((string)$order['price'], (string)$order['give_price'], 2);
  402. if (!$this->dao->update($order['id'], ['paid' => 1, 'pay_time' => time()], 'id')) {
  403. throw new ValidateException('修改订单失败');
  404. }
  405. $mark = '成功充值余额' . floatval($order['price']) . '元' . ($order['give_price'] ? ',赠送' . $order['give_price'] . '元' : '');
  406. $bill_data = ['title' => '用户余额充值', 'number' => $price, 'link_id' => $order['id'], 'balance' => $user['now_money'], 'mark' => $mark];
  407. /** @var UserBillServices $userBill */
  408. $userBill = app()->make(UserBillServices::class);
  409. $userBill->incomeNowMoney($order['uid'], 'recharge', $bill_data);
  410. $now_money = bcadd((string)$user['now_money'], (string)$price, 2);
  411. if (!$userServices->update((int)$order['uid'], ['now_money' => $now_money], 'uid')) {
  412. throw new ValidateException('修改用户信息失败');
  413. }
  414. //提醒推送
  415. event('notice.notice', [['order' => $order, 'now_money' => $now_money], 'recharge_success']);
  416. return true;
  417. }
  418. /**根据查询用户充值金额
  419. * @param array $where
  420. * @return float|int
  421. */
  422. public function getRechargeMoneyByWhere(array $where, string $rechargeSumField, string $selectType, string $group = "")
  423. {
  424. switch ($selectType) {
  425. case "sum" :
  426. return $this->dao->getWhereSumField($where, $rechargeSumField);
  427. case "group" :
  428. return $this->dao->getGroupField($where, $rechargeSumField, $group);
  429. }
  430. }
  431. }