UserRechargeServices.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  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\user\MicroPayOrderJob;
  14. use app\services\BaseServices;
  15. use app\dao\user\UserRechargeDao;
  16. use app\services\pay\PayServices;
  17. use app\services\pay\RechargeServices;
  18. use app\services\store\finance\StoreFinanceFlowServices;
  19. use app\services\system\config\SystemGroupDataServices;
  20. use crmeb\exceptions\AdminException;
  21. use crmeb\traits\ServicesTrait;
  22. use crmeb\services\{AliPayService, FormBuilder as Form, wechat\Payment};
  23. use think\exception\ValidateException;
  24. use think\facade\Route as Url;
  25. use app\services\order\StoreOrderCreateServices;
  26. use app\services\wechat\WechatUserServices;
  27. use app\webscoket\SocketPush;
  28. /**
  29. *
  30. * Class UserRechargeServices
  31. * @package app\services\user
  32. * @mixin UserRechargeDao
  33. */
  34. class UserRechargeServices extends BaseServices
  35. {
  36. use ServicesTrait;
  37. /**
  38. * UserRechargeServices constructor.
  39. * @param UserRechargeDao $dao
  40. */
  41. public function __construct(UserRechargeDao $dao)
  42. {
  43. $this->dao = $dao;
  44. }
  45. /**
  46. * 获取单条数据
  47. * @param int $id
  48. * @param array $field
  49. */
  50. public function getRecharge(int $id, array $field = [])
  51. {
  52. return $this->dao->get($id, $field);
  53. }
  54. /**
  55. * @param int $storeId
  56. * @return int
  57. */
  58. public function getRechargeCount(int $storeId)
  59. {
  60. return $this->dao->count(['store_id' => $storeId, 'paid' => 1]);
  61. }
  62. /**
  63. * 获取统计数据
  64. * @param array $where
  65. * @param string $field
  66. * @return float
  67. */
  68. public function getRechargeSum(array $where, string $field = '')
  69. {
  70. $whereData = [];
  71. if (isset($where['data'])) {
  72. $whereData['time'] = $where['data'];
  73. }
  74. if (isset($where['paid']) && $where['paid'] != '') {
  75. $whereData['paid'] = $where['paid'];
  76. }
  77. if (isset($where['nickname']) && $where['nickname']) {
  78. $whereData['like'] = $where['nickname'];
  79. }
  80. if (isset($where['recharge_type']) && $where['recharge_type']) {
  81. $whereData['recharge_type'] = $where['recharge_type'];
  82. }
  83. if (isset($where['store_id'])) {
  84. $whereData['store_id'] = $where['store_id'];
  85. }
  86. return $this->dao->getWhereSumField($whereData, $field);
  87. }
  88. /**
  89. * 获取充值列表
  90. * @param array $where
  91. * @param string $field
  92. * @param int $limit
  93. * @return array
  94. */
  95. public function getRechargeList(array $where, string $field = '*', int $limit = 0, array $with = [])
  96. {
  97. $whereData = $where;
  98. if (isset($where['data'])) {
  99. $whereData['time'] = $where['data'];
  100. unset($whereData['data']);
  101. }
  102. if (isset($where['nickname']) && $where['nickname']) {
  103. $whereData['like'] = $where['nickname'];
  104. unset($whereData['nickname']);
  105. }
  106. if ($limit) {
  107. [$page] = $this->getPageValue();
  108. } else {
  109. [$page, $limit] = $this->getPageValue();
  110. }
  111. $list = $this->dao->getList($whereData, $field, $page, $limit, $with);
  112. $count = $this->dao->count($whereData);
  113. foreach ($list as &$item) {
  114. switch ($item['recharge_type']) {
  115. case 'routine':
  116. $item['_recharge_type'] = '小程序充值';
  117. break;
  118. case 'weixin':
  119. $item['_recharge_type'] = '公众号充值';
  120. break;
  121. case 'alipay':
  122. $item['_recharge_type'] = '支付宝充值';
  123. break;
  124. case 'balance':
  125. $item['_recharge_type'] = '佣金转入';
  126. break;
  127. case 'store':
  128. $item['_recharge_type'] = '门店余额充值';
  129. break;
  130. case 'offline' :
  131. $item['_recharge_type'] = "线下支付";
  132. break;
  133. case 'cash' :
  134. $item['_recharge_type'] = "现金支付";
  135. break;
  136. default:
  137. $item['_recharge_type'] = '其他充值';
  138. break;
  139. }
  140. $item['_pay_time'] = $item['pay_time'] ? date('Y-m-d H:i:s', $item['pay_time']) : '暂无';
  141. $item['_add_time'] = $item['add_time'] ? date('Y-m-d H:i:s', $item['add_time']) : '暂无';
  142. $item['paid_type'] = $item['paid'] ? '已支付' : '未支付';
  143. unset($item['user']);
  144. }
  145. return compact('list', 'count');
  146. }
  147. /**
  148. * 获取用户充值数据
  149. * @return array
  150. */
  151. public function user_recharge(array $where)
  152. {
  153. $data = [];
  154. $where['paid'] = 1;
  155. $data['sumPrice'] = $this->getRechargeSum($where, 'price');
  156. $data['sumRefundPrice'] = $this->getRechargeSum($where, 'refund_price');
  157. $where['recharge_type'] = 'routine';
  158. $data['sumRoutinePrice'] = $this->getRechargeSum($where, 'price');
  159. $where['recharge_type'] = 'weixin';
  160. $data['sumWeixinPrice'] = $this->getRechargeSum($where, 'price');
  161. return [
  162. [
  163. 'name' => '充值总金额',
  164. 'field' => '元',
  165. 'count' => $data['sumPrice'],
  166. 'className' => 'logo-yen',
  167. 'col' => 6,
  168. ],
  169. [
  170. 'name' => '充值退款金额',
  171. 'field' => '元',
  172. 'count' => $data['sumRefundPrice'],
  173. 'className' => 'logo-usd',
  174. 'col' => 6,
  175. ],
  176. [
  177. 'name' => '小程序充值金额',
  178. 'field' => '元',
  179. 'count' => $data['sumRoutinePrice'],
  180. 'className' => 'logo-bitcoin',
  181. 'col' => 6,
  182. ],
  183. [
  184. 'name' => '公众号充值金额',
  185. 'field' => '元',
  186. 'count' => $data['sumWeixinPrice'],
  187. 'className' => 'ios-bicycle',
  188. 'col' => 6,
  189. ],
  190. ];
  191. }
  192. /**
  193. * 退款表单
  194. * @param int $id
  195. * @return mixed
  196. */
  197. public function refund_edit(int $id)
  198. {
  199. $UserRecharge = $this->getRecharge($id);
  200. if (!$UserRecharge) {
  201. throw new AdminException('数据不存在!');
  202. }
  203. if ($UserRecharge['paid'] != 1) {
  204. throw new AdminException('订单未支付');
  205. }
  206. if ($UserRecharge['price'] == $UserRecharge['refund_price']) {
  207. throw new AdminException('已退完支付金额!不能再退款了');
  208. }
  209. if ($UserRecharge['recharge_type'] == 'balance') {
  210. throw new AdminException('佣金转入余额,不能退款');
  211. }
  212. $f = array();
  213. $f[] = Form::input('order_id', '退款单号', $UserRecharge->getData('order_id'))->disabled(true);
  214. $f[] = Form::radio('refund_price', '状态', 1)->options([['label' => '本金(扣赠送余额)', 'value' => 1], ['label' => '仅本金', 'value' => 0]]);
  215. // $f[] = Form::number('refund_price', '退款金额', (float)$UserRecharge->getData('price'))->precision(2)->min(0)->max($UserRecharge->getData('price'));
  216. if ($UserRecharge['store_id']) {
  217. return create_form('退款', $f, Url::buildUrl('/order/recharge/' . $id), 'PUT');
  218. } else {
  219. return create_form('退款', $f, Url::buildUrl('/finance/recharge/' . $id), 'PUT');
  220. }
  221. }
  222. /**
  223. * 充值退款操作
  224. * @param int $id
  225. * @param $refund_price
  226. * @return mixed
  227. */
  228. public function refund_update(int $id, string $refund_price)
  229. {
  230. $UserRecharge = $this->getRecharge($id);
  231. if (!$UserRecharge) {
  232. throw new AdminException('数据不存在!');
  233. }
  234. if ($UserRecharge['price'] == $UserRecharge['refund_price']) {
  235. throw new AdminException('已退完支付金额!不能再退款了');
  236. }
  237. if ($UserRecharge['recharge_type'] == 'balance') {
  238. throw new AdminException('佣金转入余额,不能退款');
  239. }
  240. $UserRecharge = $UserRecharge->toArray();
  241. // $data['refund_price'] = bcadd($refund_price, $UserRecharge['refund_price'], 2);
  242. $data['refund_price'] = $UserRecharge['price'];
  243. // $bj = bccomp((string)$UserRecharge['price'], (string)$data['refund_price'], 2);
  244. // if ($bj < 0) {
  245. // throw new AdminException('退款金额大于支付金额,请修改退款金额');
  246. // }
  247. $refund_data['pay_price'] = $UserRecharge['price'];
  248. $refund_data['refund_price'] = $UserRecharge['price'];
  249. // $refund_data['refund_account']='REFUND_SOURCE_RECHARGE_FUNDS';
  250. if ($refund_price == 1) {
  251. $number = bcadd($UserRecharge['price'], $UserRecharge['give_price'], 2);
  252. } else {
  253. $number = $UserRecharge['price'];
  254. }
  255. try {
  256. $recharge_type = $UserRecharge['recharge_type'];
  257. if ($recharge_type == 'alipay') {
  258. mt_srand();
  259. $refund_id = $refundData['refund_id'] ?? $UserRecharge['order_id'] . rand(100, 999);
  260. //支付宝退款
  261. AliPayService::instance()->refund($UserRecharge['order_id'], $refund_data['refund_price'], $refund_id);
  262. } else if ($recharge_type == 'weixin') {
  263. //判断是不是小程序支付 TODO 之后可根据订单判断
  264. $pay_routine_open = (bool)sys_config('pay_routine_open', 0);
  265. if ($pay_routine_open) {
  266. $refund_data['refund_no'] = $UserRecharge['order_id']; // 退款订单号
  267. /** @var WechatUserServices $wechatUserServices */
  268. $wechatUserServices = app()->make(WechatUserServices::class);
  269. $refund_data['open_id'] = $wechatUserServices->value(['uid' => (int)$UserRecharge['uid']], 'openid');
  270. $refund_data['routine_order_id'] = $UserRecharge['order_id'];
  271. $refund_data['pay_routine_open'] = true;
  272. }
  273. $transaction_id = $UserRecharge['trade_no'];
  274. if (!$transaction_id) {
  275. $refund_data['type'] = 'out_trade_no';
  276. $transaction_id = $UserRecharge['order_id'];
  277. } else {
  278. $refund_data['type'] = 'transaction_id';
  279. }
  280. Payment::instance()->setAccessEnd(Payment::WEB)->payOrderRefund($transaction_id, $refund_data);
  281. } else {
  282. $transaction_id = $UserRecharge['trade_no'];
  283. if (!$transaction_id) {
  284. $refund_data['type'] = 'out_trade_no';
  285. $transaction_id = $UserRecharge['order_id'];
  286. } else {
  287. $refund_data['type'] = 'transaction_id';
  288. }
  289. Payment::instance()->setAccessEnd(Payment::MINI)->payOrderRefund($transaction_id, $refund_data);
  290. }
  291. } catch (\Exception $e) {
  292. throw new AdminException($e->getMessage());
  293. }
  294. if (!$this->dao->update($id, $data)) {
  295. throw new AdminException('修改提现数据失败');
  296. }
  297. /** @var UserServices $userServices */
  298. $userServices = app()->make(UserServices::class);
  299. $userInfo = $userServices->getUserInfo((int)$UserRecharge['uid']);
  300. if ($userInfo['now_money'] > $number) {
  301. $now_money = bcsub((string)$userInfo['now_money'], $number, 2);
  302. } else {
  303. $number = $userInfo['now_money'];
  304. $now_money = 0;
  305. }
  306. //修改用户余额
  307. $userServices->update((int)$UserRecharge['uid'], ['now_money' => $now_money], 'uid');
  308. $UserRecharge['nickname'] = $userInfo['nickname'];
  309. $UserRecharge['phone'] = $userInfo['phone'];
  310. $UserRecharge['now_money'] = $userInfo['now_money'];
  311. /** @var UserMoneyServices $userMoneyServices */
  312. $userMoneyServices = app()->make(UserMoneyServices::class);
  313. //保存余额记录
  314. $userMoneyServices->income('user_recharge_refund', $UserRecharge['uid'], $number, $now_money, $id);
  315. //充值退款事件
  316. event('user.rechargeRefund', [$UserRecharge, $data]);
  317. return true;
  318. }
  319. /**
  320. * 删除
  321. * @param int $id
  322. * @return bool
  323. */
  324. public function delRecharge(int $id)
  325. {
  326. $rechargInfo = $this->getRecharge($id);
  327. if (!$rechargInfo) throw new AdminException('订单未找到');
  328. if ($rechargInfo->paid) {
  329. throw new AdminException('已支付的订单记录无法删除');
  330. }
  331. if ($this->dao->delete($id))
  332. return true;
  333. else
  334. throw new AdminException('删除失败');
  335. }
  336. /**
  337. * 生成充值订单号
  338. * @return bool|string
  339. */
  340. public function getOrderId()
  341. {
  342. return 'wx' . date('YmdHis', time()) . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
  343. }
  344. /**
  345. * 导入佣金到余额
  346. * @param int $uid
  347. * @param $price
  348. * @return bool
  349. */
  350. public function importNowMoney(int $uid, $price)
  351. {
  352. $switch = sys_config('brokerage_to_money_switch', 1);
  353. if (!$switch) throw new ValidateException('暂不支持');
  354. /** @var UserServices $userServices */
  355. $userServices = app()->make(UserServices::class);
  356. $user = $userServices->getUserInfo($uid);
  357. if (!$user) {
  358. throw new ValidateException('数据不存在');
  359. }
  360. /** @var UserBrokerageServices $userBrokerageServices */
  361. $userBrokerageServices = app()->make(UserBrokerageServices::class);
  362. $broken_commission = $userBrokerageServices->getUserFrozenPrice($uid);
  363. $commissionCount = bcsub((string)$user['brokerage_price'], (string)$broken_commission, 2);
  364. if ($price > $commissionCount) {
  365. throw new ValidateException('转入金额不能大于可提现佣金!');
  366. }
  367. return $this->transaction(function () use ($uid, $user, $price, $userServices) {
  368. $edit_data = [];
  369. $edit_data['now_money'] = bcadd((string)$user['now_money'], (string)$price, 2);
  370. $edit_data['brokerage_price'] = $user['brokerage_price'] > $price ? bcsub((string)$user['brokerage_price'], (string)$price, 2) : 0;
  371. //修改用户佣金、余额信息
  372. $userServices->update($uid, $edit_data, 'uid');
  373. //写入充值记录
  374. $rechargeInfo = [
  375. 'uid' => $uid,
  376. 'order_id' => $this->getOrderId(),
  377. 'recharge_type' => 'balance',
  378. 'price' => $price,
  379. 'give_price' => 0,
  380. 'paid' => 1,
  381. 'pay_time' => time(),
  382. 'add_time' => time()
  383. ];
  384. //写入充值记录
  385. $re = $this->dao->save($rechargeInfo);
  386. /** @var UserMoneyServices $userMoneyServices */
  387. $userMoneyServices = app()->make(UserMoneyServices::class);
  388. //余额记录
  389. $userMoneyServices->income('brokerage_to_nowMoney', $uid, $price, $edit_data['now_money'], $re['id']);
  390. $extractInfo = [
  391. 'uid' => $uid,
  392. 'real_name' => $user['nickname'],
  393. 'extract_type' => 'balance',
  394. 'extract_price' => $price,
  395. 'balance' => $edit_data['brokerage_price'],
  396. 'add_time' => time(),
  397. 'status' => 1
  398. ];
  399. /** @var UserExtractServices $userExtract */
  400. $userExtract = app()->make(UserExtractServices::class);
  401. //写入提现记录
  402. $userExtract->save($extractInfo);
  403. //佣金提现记录
  404. /** @var UserBrokerageServices $userBrokerageServices */
  405. $userBrokerageServices = app()->make(UserBrokerageServices::class);
  406. $userBrokerageServices->income('brokerage_to_nowMoney', $uid, $price, $edit_data['brokerage_price'], $re['id']);
  407. });
  408. }
  409. /**
  410. * 申请充值
  411. * @param int $uid
  412. * @param $price
  413. * @param $recharId
  414. * @param $type
  415. * @param $from
  416. * @param array $staffinfo
  417. * @param string $authCode 扫码code
  418. * @return array
  419. * @throws \think\db\exception\DataNotFoundException
  420. * @throws \think\db\exception\ModelNotFoundException
  421. */
  422. public function recharge(int $uid, $price, $recharId, $type, $from, array $staffinfo = [], string $authCode = '')
  423. {
  424. /** @var UserServices $userServices */
  425. $userServices = app()->make(UserServices::class);
  426. $user = $userServices->getUserInfo($uid);
  427. if (!$user) {
  428. throw new ValidateException('数据不存在');
  429. }
  430. $paid_price = 0;
  431. if ($recharId) {
  432. /** @var SystemGroupDataServices $systemGroupData */
  433. $systemGroupData = app()->make(SystemGroupDataServices::class);
  434. $data = $systemGroupData->getDateValue($recharId);
  435. if (!$data) {
  436. return app('json')->fail('您选择的充值方式已下架!');
  437. } else {
  438. $paid_price = $data['give_money'] ?? 0;
  439. }
  440. $price = $data['price'];
  441. }
  442. switch ((int)$type) {
  443. case 0: //支付充值余额
  444. /** @var StoreOrderCreateServices $orderCreateServices */
  445. $orderCreateServices = app()->make(StoreOrderCreateServices::class);
  446. $recharge_data = [];
  447. $recharge_data['order_id'] = $orderCreateServices->getNewOrderId('cz');
  448. $recharge_data['uid'] = $uid;
  449. $recharge_data['price'] = $price;
  450. $recharge_data['recharge_type'] = $from;
  451. $recharge_data['paid'] = 0;
  452. $recharge_data['add_time'] = time();
  453. $recharge_data['give_price'] = $paid_price;
  454. $recharge_data['channel_type'] = $user['user_type'];
  455. if (!$rechargeOrder = $this->dao->save($recharge_data)) {
  456. throw new ValidateException('充值订单生成失败');
  457. }
  458. try {
  459. /** @var RechargeServices $recharge */
  460. $recharge = app()->make(RechargeServices::class);
  461. $order_info = $recharge->recharge((int)$rechargeOrder->id);
  462. } catch (\Exception $e) {
  463. throw new ValidateException($e->getMessage());
  464. }
  465. return ['msg' => '', 'type' => $from, 'data' => $order_info];
  466. break;
  467. case 1: //佣金转入余额
  468. $this->importNowMoney($uid, $price);
  469. return ['msg' => '转入余额成功', 'type' => $from, 'data' => []];
  470. break;
  471. case 2://门店充值-用户扫码付款
  472. case 3://门店充值-付款码付款
  473. if (!$staffinfo) {
  474. throw new ValidateException('请稍后重试');
  475. }
  476. $recharge_data = [];
  477. $recharge_data['order_id'] = $this->getOrderId();
  478. $recharge_data['uid'] = $uid;
  479. $recharge_data['store_id'] = $staffinfo['store_id'];
  480. $recharge_data['staff_id'] = $staffinfo['id'];
  481. $recharge_data['price'] = $price;
  482. //自动判定支付方式
  483. if ($authCode) {
  484. $recharge_data['auth_code'] = $authCode;
  485. if (Payment::isWechatAuthCode($authCode)) {
  486. $recharge_data['recharge_type'] = PayServices::WEIXIN_PAY;
  487. } else if (AliPayService::isAliPayAuthCode($authCode)) {
  488. $recharge_data['recharge_type'] = PayServices::ALIAPY_PAY;
  489. } else {
  490. throw new ValidateException('付款二维码错误');
  491. }
  492. } else {
  493. $recharge_data['recharge_type'] = $from;
  494. }
  495. $recharge_data['paid'] = 0;
  496. $recharge_data['add_time'] = time();
  497. $recharge_data['give_price'] = $paid_price;
  498. $recharge_data['channel_type'] = $user['user_type'];
  499. if (!$rechargeOrder = $this->dao->save($recharge_data)) {
  500. throw new ValidateException('充值订单生成失败');
  501. }
  502. try {
  503. /** @var RechargeServices $recharge */
  504. $recharge = app()->make(RechargeServices::class);
  505. $order_info = $recharge->recharge((int)$rechargeOrder->id, $authCode);
  506. if ($type === 3) {
  507. if ($order_info['paid'] === 1) {
  508. //修改支付状态
  509. $this->rechargeSuccess($recharge_data['order_id']);
  510. return [
  511. 'msg' => $order_info['message'],
  512. 'status' => 'SUCCESS',
  513. 'type' => $from,
  514. 'payInfo' => [],
  515. 'data' => [
  516. 'jsConfig' => [],
  517. 'order_id' => $recharge_data['order_id']
  518. ]
  519. ];
  520. } else {
  521. //发起支付但是还没有支付,需要在5秒后查询支付状态
  522. if ($recharge_data['recharge_type'] === PayServices::WEIXIN_PAY) {
  523. if (isset($order_info['payInfo']['err_code']) && in_array($order_info['payInfo']['err_code'], ['AUTH_CODE_INVALID', 'NOTENOUGH'])) {
  524. return ['status' => 'ERROR', 'msg' => '支付失败', 'payInfo' => $order_info];
  525. }
  526. $secs = 5;
  527. if (isset($order_info['payInfo']['err_code']) && $order_info['payInfo']['err_code'] === 'USERPAYING') {
  528. $secs = 10;
  529. }
  530. MicroPayOrderJob::dispatchSece($secs, [$recharge_data['order_id']]);
  531. }
  532. return [
  533. 'msg' => $order_info['message'] ?? '等待支付中',
  534. 'status' => 'PAY_ING',
  535. 'type' => $from,
  536. 'payInfo' => $order_info,
  537. 'data' => [
  538. 'jsConfig' => [],
  539. 'order_id' => $recharge_data['order_id']
  540. ]
  541. ];
  542. }
  543. }
  544. } catch (\Exception $e) {
  545. \think\facade\Log::error('充值失败,原因:' . $e->getMessage());
  546. throw new ValidateException('充值失败:' . $e->getMessage());
  547. }
  548. return ['msg' => '', 'status' => 'PAY', 'type' => $from, 'data' => ['jsConfig' => $order_info, 'order_id' => $recharge_data['order_id']]];
  549. break;
  550. case 4: //现金支付
  551. if (!$staffinfo) {
  552. throw new ValidateException('请稍后重试');
  553. }
  554. /** @var StoreOrderCreateServices $orderCreateServices */
  555. $orderCreateServices = app()->make(StoreOrderCreateServices::class);
  556. $recharge_data = [];
  557. $recharge_data['order_id'] = $orderCreateServices->getNewOrderId('cz');
  558. $recharge_data['uid'] = $uid;
  559. $recharge_data['price'] = $price;
  560. $recharge_data['store_id'] = $staffinfo['store_id'];
  561. $recharge_data['staff_id'] = $staffinfo['id'];
  562. $recharge_data['recharge_type'] = PayServices::CASH_PAY;
  563. $recharge_data['paid'] = 0;
  564. $recharge_data['add_time'] = time();
  565. $recharge_data['give_price'] = $paid_price;
  566. $recharge_data['channel_type'] = $user['user_type'];
  567. if (!$rechargeOrder = $this->dao->save($recharge_data)) {
  568. throw new ValidateException('充值订单生成失败');
  569. }
  570. try {
  571. //修改支付状态
  572. $this->rechargeSuccess($recharge_data['order_id']);
  573. } catch (\Exception $e) {
  574. throw new ValidateException($e->getMessage());
  575. }
  576. return ['msg' => '', 'status' => 'SUCCESS', 'type' => $from, 'data' => ['order_id' => $recharge_data['order_id']]];
  577. break;
  578. default:
  579. throw new ValidateException('缺少参数');
  580. break;
  581. }
  582. }
  583. /**
  584. * 用户充值成功
  585. * @param $orderId
  586. * @return bool
  587. * @throws \think\Exception
  588. * @throws \think\db\exception\DataNotFoundException
  589. * @throws \think\db\exception\DbException
  590. * @throws \think\db\exception\ModelNotFoundException
  591. */
  592. public function rechargeSuccess($orderId, array $other = [])
  593. {
  594. $order = $this->dao->getOne(['order_id' => $orderId, 'paid' => 0]);
  595. if (!$order) {
  596. throw new ValidateException('订单失效或者不存在');
  597. }
  598. $order = $order->toArray();
  599. /** @var UserServices $userServices */
  600. $userServices = app()->make(UserServices::class);
  601. $user = $userServices->getUserInfo((int)$order['uid']);
  602. if (!$user) {
  603. throw new ValidateException('数据不存在');
  604. }
  605. $price = bcadd((string)$order['price'], (string)$order['give_price'], 2);
  606. if (!$this->dao->update($order['id'], ['paid' => 1, 'pay_time' => time(), 'trade_no' => $other['trade_no'] ?? ''], 'id')) {
  607. throw new ValidateException('修改订单失败');
  608. }
  609. $now_money = bcadd((string)$user['now_money'], (string)$price, 2);
  610. /** @var UserMoneyServices $userMoneyServices */
  611. $userMoneyServices = app()->make(UserMoneyServices::class);
  612. $userMoneyServices->income('user_recharge', $user['uid'], ['number' => $price, 'price' => $order['price'], 'give_price' => $order['give_price']], $now_money, $order['id']);
  613. if (!$userServices->update((int)$order['uid'], ['now_money' => $now_money], 'uid')) {
  614. throw new ValidateException('修改用户信息失败');
  615. }
  616. //记录流水账单
  617. if ($order['store_id'] > 0) {
  618. $data = $order;
  619. $data['pay_time'] = time();
  620. /** @var StoreFinanceFlowServices $storeFinanceFlowServices */
  621. $storeFinanceFlowServices = app()->make(StoreFinanceFlowServices::class);
  622. $storeFinanceFlowServices->setFinance($data, 2);
  623. }
  624. $order['nickname'] = $user['nickname'];
  625. $order['phone'] = $user['phone'];
  626. if ($order['staff_id']) {
  627. //发送消息
  628. try {
  629. SocketPush::instance()->to($order['staff_id'])->setUserType('cashier')->type('changUser')->data(['uid' => $user['uid']])->push();
  630. } catch (\Throwable $e) {
  631. }
  632. }
  633. //用户充值成功事件
  634. event('user.recharge', [$order, $now_money]);
  635. return true;
  636. }
  637. /**
  638. * 根据查询用户充值金额
  639. * @param array $where
  640. * @return float|int
  641. */
  642. public function getRechargeMoneyByWhere(array $where, string $rechargeSumField, string $selectType, string $group = "")
  643. {
  644. switch ($selectType) {
  645. case "sum" :
  646. return $this->dao->getWhereSumField($where, $rechargeSumField);
  647. case "group" :
  648. return $this->dao->getGroupField($where, $rechargeSumField, $group);
  649. }
  650. }
  651. /**
  652. * 充值每日统计数据
  653. * @param int $store_id
  654. * @param int $staff_id
  655. * @param array $time
  656. * @return array
  657. */
  658. public function getDataPriceCount(int $store_id, int $staff_id = 0, $time = [])
  659. {
  660. [$page, $limit] = $this->getPageValue();
  661. $where = ['store_id' => $store_id, 'paid' => 1, 'time' => $time];
  662. if ($staff_id) {
  663. $where['staff_id'] = $staff_id;
  664. }
  665. return $this->dao->getDataPriceCount($where, ['sum(price) as price', 'count(id) as count', 'FROM_UNIXTIME(add_time, \'%m-%d\') as time'], $page, $limit);
  666. }
  667. /**
  668. * 门店充值统计详情列表
  669. * @param int $store_id
  670. * @param int $staff_id
  671. * @param array $time
  672. * @return array|array[]
  673. */
  674. public function time(int $store_id, int $staff_id, array $time = [])
  675. {
  676. if (!$time) {
  677. return [[], []];
  678. }
  679. [$start, $stop, $front, $front_stop] = $time;
  680. $where = ['store_id' => $store_id, 'paid' => 1];
  681. if ($staff_id) $where['staff_id'] = $staff_id;
  682. $frontPrice = $this->dao->sum($where + ['time' => [$front, $front_stop]], 'price', true);
  683. $nowPrice = $this->dao->sum($where + ['time' => [$start, $stop]], 'price', true);
  684. [$page, $limit] = $this->getPageValue();
  685. $list = $this->dao->getList($where + ['time' => [$start, $stop]], 'id,uid,order_id,price,add_time', $page, $limit);
  686. foreach ($list as &$item) {
  687. $item['add_time'] = $item['add_time'] ? date('Y-m-d H:i:s', $item['add_time']) : '';
  688. }
  689. return [[$nowPrice, $frontPrice], $list];
  690. }
  691. }