UserRechargeServices.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  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. /** @var UserServices $userServices */
  353. $userServices = app()->make(UserServices::class);
  354. $user = $userServices->getUserInfo($uid);
  355. if (!$user) {
  356. throw new ValidateException('数据不存在');
  357. }
  358. /** @var UserBrokerageServices $userBrokerageServices */
  359. $userBrokerageServices = app()->make(UserBrokerageServices::class);
  360. $broken_commission = $userBrokerageServices->getUserFrozenPrice($uid);
  361. $commissionCount = bcsub((string)$user['brokerage_price'], (string)$broken_commission, 2);
  362. if ($price > $commissionCount) {
  363. throw new ValidateException('转入金额不能大于可提现佣金!');
  364. }
  365. return $this->transaction(function () use ($uid, $user, $price, $userServices) {
  366. $edit_data = [];
  367. $edit_data['now_money'] = bcadd((string)$user['now_money'], (string)$price, 2);
  368. $edit_data['brokerage_price'] = $user['brokerage_price'] > $price ? bcsub((string)$user['brokerage_price'], (string)$price, 2) : 0;
  369. //修改用户佣金、余额信息
  370. $userServices->update($uid, $edit_data, 'uid');
  371. //写入充值记录
  372. $rechargeInfo = [
  373. 'uid' => $uid,
  374. 'order_id' => $this->getOrderId(),
  375. 'recharge_type' => 'balance',
  376. 'price' => $price,
  377. 'give_price' => 0,
  378. 'paid' => 1,
  379. 'pay_time' => time(),
  380. 'add_time' => time()
  381. ];
  382. //写入充值记录
  383. $re = $this->dao->save($rechargeInfo);
  384. /** @var UserMoneyServices $userMoneyServices */
  385. $userMoneyServices = app()->make(UserMoneyServices::class);
  386. //余额记录
  387. $userMoneyServices->income('brokerage_to_nowMoney', $uid, $price, $edit_data['now_money'], $re['id']);
  388. $extractInfo = [
  389. 'uid' => $uid,
  390. 'real_name' => $user['nickname'],
  391. 'extract_type' => 'balance',
  392. 'extract_price' => $price,
  393. 'balance' => $edit_data['brokerage_price'],
  394. 'add_time' => time(),
  395. 'status' => 1
  396. ];
  397. /** @var UserExtractServices $userExtract */
  398. $userExtract = app()->make(UserExtractServices::class);
  399. //写入提现记录
  400. $userExtract->save($extractInfo);
  401. //佣金提现记录
  402. /** @var UserBrokerageServices $userBrokerageServices */
  403. $userBrokerageServices = app()->make(UserBrokerageServices::class);
  404. $userBrokerageServices->income('brokerage_to_nowMoney', $uid, $price, $edit_data['brokerage_price'], $re['id']);
  405. });
  406. }
  407. /**
  408. * 申请充值
  409. * @param int $uid
  410. * @param $price
  411. * @param $recharId
  412. * @param $type
  413. * @param $from
  414. * @param array $staffinfo
  415. * @param string $authCode 扫码code
  416. * @return array
  417. * @throws \think\db\exception\DataNotFoundException
  418. * @throws \think\db\exception\ModelNotFoundException
  419. */
  420. public function recharge(int $uid, $price, $recharId, $type, $from, array $staffinfo = [], string $authCode = '')
  421. {
  422. /** @var UserServices $userServices */
  423. $userServices = app()->make(UserServices::class);
  424. $user = $userServices->getUserInfo($uid);
  425. if (!$user) {
  426. throw new ValidateException('数据不存在');
  427. }
  428. $paid_price = 0;
  429. if ($recharId) {
  430. /** @var SystemGroupDataServices $systemGroupData */
  431. $systemGroupData = app()->make(SystemGroupDataServices::class);
  432. $data = $systemGroupData->getDateValue($recharId);
  433. if (!$data) {
  434. return app('json')->fail('您选择的充值方式已下架!');
  435. } else {
  436. $paid_price = $data['give_money'] ?? 0;
  437. }
  438. $price = $data['price'];
  439. }
  440. switch ((int)$type) {
  441. case 0: //支付充值余额
  442. /** @var StoreOrderCreateServices $orderCreateServices */
  443. $orderCreateServices = app()->make(StoreOrderCreateServices::class);
  444. $recharge_data = [];
  445. $recharge_data['order_id'] = $orderCreateServices->getNewOrderId('cz');
  446. $recharge_data['uid'] = $uid;
  447. $recharge_data['price'] = $price;
  448. $recharge_data['recharge_type'] = $from;
  449. $recharge_data['paid'] = 0;
  450. $recharge_data['add_time'] = time();
  451. $recharge_data['give_price'] = $paid_price;
  452. $recharge_data['channel_type'] = $user['user_type'];
  453. if (!$rechargeOrder = $this->dao->save($recharge_data)) {
  454. throw new ValidateException('充值订单生成失败');
  455. }
  456. try {
  457. /** @var RechargeServices $recharge */
  458. $recharge = app()->make(RechargeServices::class);
  459. $order_info = $recharge->recharge((int)$rechargeOrder->id);
  460. } catch (\Exception $e) {
  461. throw new ValidateException($e->getMessage());
  462. }
  463. return ['msg' => '', 'type' => $from, 'data' => $order_info];
  464. break;
  465. case 1: //佣金转入余额
  466. $this->importNowMoney($uid, $price);
  467. return ['msg' => '转入余额成功', 'type' => $from, 'data' => []];
  468. break;
  469. case 2://门店充值-用户扫码付款
  470. case 3://门店充值-付款码付款
  471. if (!$staffinfo) {
  472. throw new ValidateException('请稍后重试');
  473. }
  474. $recharge_data = [];
  475. $recharge_data['order_id'] = $this->getOrderId();
  476. $recharge_data['uid'] = $uid;
  477. $recharge_data['store_id'] = $staffinfo['store_id'];
  478. $recharge_data['staff_id'] = $staffinfo['id'];
  479. $recharge_data['price'] = $price;
  480. //自动判定支付方式
  481. if ($authCode) {
  482. $recharge_data['auth_code'] = $authCode;
  483. if (Payment::isWechatAuthCode($authCode)) {
  484. $recharge_data['recharge_type'] = PayServices::WEIXIN_PAY;
  485. } else if (AliPayService::isAliPayAuthCode($authCode)) {
  486. $recharge_data['recharge_type'] = PayServices::ALIAPY_PAY;
  487. } else {
  488. throw new ValidateException('付款二维码错误');
  489. }
  490. } else {
  491. $recharge_data['recharge_type'] = $from;
  492. }
  493. $recharge_data['paid'] = 0;
  494. $recharge_data['add_time'] = time();
  495. $recharge_data['give_price'] = $paid_price;
  496. $recharge_data['channel_type'] = $user['user_type'];
  497. if (!$rechargeOrder = $this->dao->save($recharge_data)) {
  498. throw new ValidateException('充值订单生成失败');
  499. }
  500. try {
  501. /** @var RechargeServices $recharge */
  502. $recharge = app()->make(RechargeServices::class);
  503. $order_info = $recharge->recharge((int)$rechargeOrder->id, $authCode);
  504. if ($type === 3) {
  505. if ($order_info['paid'] === 1) {
  506. //修改支付状态
  507. $this->rechargeSuccess($recharge_data['order_id']);
  508. return [
  509. 'msg' => $order_info['message'],
  510. 'status' => 'SUCCESS',
  511. 'type' => $from,
  512. 'payInfo' => [],
  513. 'data' => [
  514. 'jsConfig' => [],
  515. 'order_id' => $recharge_data['order_id']
  516. ]
  517. ];
  518. } else {
  519. //发起支付但是还没有支付,需要在5秒后查询支付状态
  520. if ($recharge_data['recharge_type'] === PayServices::WEIXIN_PAY) {
  521. if (isset($order_info['payInfo']['err_code']) && in_array($order_info['payInfo']['err_code'], ['AUTH_CODE_INVALID', 'NOTENOUGH'])) {
  522. return ['status' => 'ERROR', 'msg' => '支付失败', 'payInfo' => $order_info];
  523. }
  524. $secs = 5;
  525. if (isset($order_info['payInfo']['err_code']) && $order_info['payInfo']['err_code'] === 'USERPAYING') {
  526. $secs = 10;
  527. }
  528. MicroPayOrderJob::dispatchSece($secs, [$recharge_data['order_id']]);
  529. }
  530. return [
  531. 'msg' => $order_info['message'] ?? '等待支付中',
  532. 'status' => 'PAY_ING',
  533. 'type' => $from,
  534. 'payInfo' => $order_info,
  535. 'data' => [
  536. 'jsConfig' => [],
  537. 'order_id' => $recharge_data['order_id']
  538. ]
  539. ];
  540. }
  541. }
  542. } catch (\Exception $e) {
  543. \think\facade\Log::error('充值失败,原因:' . $e->getMessage());
  544. throw new ValidateException('充值失败:' . $e->getMessage());
  545. }
  546. return ['msg' => '', 'status' => 'PAY', 'type' => $from, 'data' => ['jsConfig' => $order_info, 'order_id' => $recharge_data['order_id']]];
  547. break;
  548. case 4: //现金支付
  549. if (!$staffinfo) {
  550. throw new ValidateException('请稍后重试');
  551. }
  552. /** @var StoreOrderCreateServices $orderCreateServices */
  553. $orderCreateServices = app()->make(StoreOrderCreateServices::class);
  554. $recharge_data = [];
  555. $recharge_data['order_id'] = $orderCreateServices->getNewOrderId('cz');
  556. $recharge_data['uid'] = $uid;
  557. $recharge_data['price'] = $price;
  558. $recharge_data['store_id'] = $staffinfo['store_id'];
  559. $recharge_data['staff_id'] = $staffinfo['id'];
  560. $recharge_data['recharge_type'] = PayServices::CASH_PAY;
  561. $recharge_data['paid'] = 0;
  562. $recharge_data['add_time'] = time();
  563. $recharge_data['give_price'] = $paid_price;
  564. $recharge_data['channel_type'] = $user['user_type'];
  565. if (!$rechargeOrder = $this->dao->save($recharge_data)) {
  566. throw new ValidateException('充值订单生成失败');
  567. }
  568. try {
  569. //修改支付状态
  570. $this->rechargeSuccess($recharge_data['order_id']);
  571. } catch (\Exception $e) {
  572. throw new ValidateException($e->getMessage());
  573. }
  574. return ['msg' => '','status' => 'SUCCESS', 'type' => $from, 'data' => ['order_id' => $recharge_data['order_id']]];
  575. break;
  576. default:
  577. throw new ValidateException('缺少参数');
  578. break;
  579. }
  580. }
  581. /**
  582. * 用户充值成功
  583. * @param $orderId
  584. * @return bool
  585. * @throws \think\Exception
  586. * @throws \think\db\exception\DataNotFoundException
  587. * @throws \think\db\exception\DbException
  588. * @throws \think\db\exception\ModelNotFoundException
  589. */
  590. public function rechargeSuccess($orderId, array $other = [])
  591. {
  592. $order = $this->dao->getOne(['order_id' => $orderId, 'paid' => 0]);
  593. if (!$order) {
  594. throw new ValidateException('订单失效或者不存在');
  595. }
  596. $order = $order->toArray();
  597. /** @var UserServices $userServices */
  598. $userServices = app()->make(UserServices::class);
  599. $user = $userServices->getUserInfo((int)$order['uid']);
  600. if (!$user) {
  601. throw new ValidateException('数据不存在');
  602. }
  603. $price = bcadd((string)$order['price'], (string)$order['give_price'], 2);
  604. if (!$this->dao->update($order['id'], ['paid' => 1, 'pay_time' => time(), 'trade_no' => $other['trade_no'] ?? ''], 'id')) {
  605. throw new ValidateException('修改订单失败');
  606. }
  607. $now_money = bcadd((string)$user['now_money'], (string)$price, 2);
  608. /** @var UserMoneyServices $userMoneyServices */
  609. $userMoneyServices = app()->make(UserMoneyServices::class);
  610. $userMoneyServices->income('user_recharge', $user['uid'], ['number' => $price, 'price' => $order['price'], 'give_price' => $order['give_price']], $now_money, $order['id']);
  611. if (!$userServices->update((int)$order['uid'], ['now_money' => $now_money], 'uid')) {
  612. throw new ValidateException('修改用户信息失败');
  613. }
  614. //记录流水账单
  615. if ($order['store_id'] > 0) {
  616. $data = $order;
  617. $data['pay_time'] = time();
  618. /** @var StoreFinanceFlowServices $storeFinanceFlowServices */
  619. $storeFinanceFlowServices = app()->make(StoreFinanceFlowServices::class);
  620. $storeFinanceFlowServices->setFinance($data, 2);
  621. }
  622. $order['nickname'] = $user['nickname'];
  623. $order['phone'] = $user['phone'];
  624. if ($order['staff_id']) {
  625. //发送消息
  626. try {
  627. SocketPush::instance()->to($order['staff_id'])->setUserType('cashier')->type('changUser')->data(['uid' => $user['uid']])->push();
  628. } catch (\Throwable $e) {
  629. }
  630. }
  631. //用户充值成功事件
  632. event('user.recharge', [$order, $now_money]);
  633. return true;
  634. }
  635. /**
  636. * 根据查询用户充值金额
  637. * @param array $where
  638. * @return float|int
  639. */
  640. public function getRechargeMoneyByWhere(array $where, string $rechargeSumField, string $selectType, string $group = "")
  641. {
  642. switch ($selectType) {
  643. case "sum" :
  644. return $this->dao->getWhereSumField($where, $rechargeSumField);
  645. case "group" :
  646. return $this->dao->getGroupField($where, $rechargeSumField, $group);
  647. }
  648. }
  649. /**
  650. * 充值每日统计数据
  651. * @param int $store_id
  652. * @param int $staff_id
  653. * @param array $time
  654. * @return array
  655. */
  656. public function getDataPriceCount(int $store_id, int $staff_id = 0, $time = [])
  657. {
  658. [$page, $limit] = $this->getPageValue();
  659. $where = ['store_id' => $store_id, 'paid' => 1, 'time' => $time];
  660. if ($staff_id) {
  661. $where['staff_id'] = $staff_id;
  662. }
  663. return $this->dao->getDataPriceCount($where, ['sum(price) as price', 'count(id) as count', 'FROM_UNIXTIME(add_time, \'%m-%d\') as time'], $page, $limit);
  664. }
  665. /**
  666. * 门店充值统计详情列表
  667. * @param int $store_id
  668. * @param int $staff_id
  669. * @param array $time
  670. * @return array|array[]
  671. */
  672. public function time(int $store_id, int $staff_id, array $time = [])
  673. {
  674. if (!$time) {
  675. return [[], []];
  676. }
  677. [$start, $stop, $front, $front_stop] = $time;
  678. $where = ['store_id' => $store_id, 'paid' => 1];
  679. if ($staff_id) $where['staff_id'] = $staff_id;
  680. $frontPrice = $this->dao->sum($where + ['time' => [$front, $front_stop]], 'price', true);
  681. $nowPrice = $this->dao->sum($where + ['time' => [$start, $stop]], 'price', true);
  682. [$page, $limit] = $this->getPageValue();
  683. $list = $this->dao->getList($where + ['time' => [$start, $stop]], 'id,uid,order_id,price,add_time', $page, $limit);
  684. foreach ($list as &$item) {
  685. $item['add_time'] = $item['add_time'] ? date('Y-m-d H:i:s', $item['add_time']) : '';
  686. }
  687. return [[$nowPrice, $frontPrice], $list];
  688. }
  689. }