TradeOrderService.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | LARAVEL8.0 框架 [ LARAVEL ][ RXThinkCMF ]
  4. // +----------------------------------------------------------------------
  5. // | 版权所有 2017~2021 LARAVEL研发中心
  6. // +----------------------------------------------------------------------
  7. // | 官方网站: http://www.laravel.cn
  8. // +----------------------------------------------------------------------
  9. // | Author: laravel开发员 <laravel.qq.com>
  10. // +----------------------------------------------------------------------
  11. namespace App\Services\Common;
  12. use App\Models\CapitalLogModel;
  13. use App\Models\MemberModel;
  14. use App\Models\TradeOrderModel;
  15. use App\Services\Api\MemberPaymentService;
  16. use App\Services\BaseService;
  17. use App\Services\ConfigService;
  18. /**
  19. * 用户交易订单-服务类
  20. * Class TradeOrderService
  21. * @package App\Services\Common
  22. */
  23. class TradeOrderService extends BaseService
  24. {
  25. // 静态对象
  26. protected static $instance = null;
  27. /**
  28. * 构造函数
  29. * @since 2020/11/10
  30. * TradeOrderService constructor.
  31. */
  32. public function __construct()
  33. {
  34. $this->model = new TradeOrderModel();
  35. $this->memberModel = new MemberModel();
  36. $this->capitalModel = new CapitalLogModel();
  37. }
  38. /**
  39. * 静态入口
  40. * @return static|null
  41. */
  42. public static function make()
  43. {
  44. if (!self::$instance) {
  45. self::$instance = (new static());
  46. }
  47. return self::$instance;
  48. }
  49. /**
  50. * 订单列表
  51. * @param $params
  52. * @param int $pageSize
  53. * @return array
  54. */
  55. public function getDataList($params, $pageSize = 15)
  56. {
  57. $list = $this->model->from('trade_order as a')
  58. ->leftJoin('member as b', 'b.id', '=', 'a.user_id')
  59. ->where(function ($query) use ($params) {
  60. $query->where(['a.mark' => 1])->where('a.status', '>', 0);
  61. $orderNo = isset($params['order_no']) && $params['order_no'] ? trim($params['order_no']) : '';
  62. if ($orderNo) {
  63. $query->where('a.order_no', 'like', "%{$orderNo}%");
  64. }
  65. $type = isset($params['type']) ? intval($params['type']) : 0;
  66. if ($type > 0) {
  67. $query->where(['a.type' => $type]);
  68. }
  69. // 日期
  70. $date = isset($params['date']) ? $params['date'] : '';
  71. if ($date) {
  72. }
  73. $exceptionStatus = isset($params['exception_status']) ? intval($params['exception_status']) : 0;
  74. if ($exceptionStatus > 0) {
  75. $query->where(['a.exception_status' => $exceptionStatus]);
  76. }
  77. $userId = isset($params['user_id']) ? $params['user_id'] : 0;
  78. if ($userId > 0) {
  79. $query->where('a.user_id', $userId);
  80. }
  81. $businessId = isset($params['business_id']) ? $params['business_id'] : 0;
  82. if ($businessId > 0) {
  83. $query->where('a.business_id', $businessId);
  84. }
  85. })
  86. ->select(['a.*', 'b.username'])
  87. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  88. $list = $list ? $list->toArray() : [];
  89. if ($list) {
  90. $overTime = ConfigService::make()->getConfigByCode('trade_order_overtime');
  91. $overTime = $overTime ? $overTime : 0;
  92. foreach ($list['data'] as &$item) {
  93. $item['idcardData'] = $item['idcard_data'] ? json_decode($item['idcard_data'], true) : [];
  94. $item['paymentData'] = $item['payment_data'] ? json_decode($item['payment_data'], true) : [];
  95. $item['create_time_text'] = $item['create_time'] ? datetime($item['create_time'], 'Y-m-d H:i') : '';
  96. $item['time_text'] = $item['create_time'] ? datetime($item['create_time'], 'H:i') : '';
  97. $item['pay_time_text'] = $item['pay_time'] ? datetime($item['pay_time'], 'Y-m-d H:i') : '';
  98. $item['username_text'] = $item['username'] ? format_account($item['username']) : '';
  99. $overTime = max(0, intval($item['create_time']) + $overTime * 60 - time());
  100. $item['overtime_text'] = in_array($item['status'], [1, 2]) && $overTime ? date('H:i', $overTime) : '';
  101. }
  102. }
  103. return [
  104. 'pageSize' => $pageSize,
  105. 'total' => isset($list['total']) ? $list['total'] : 0,
  106. 'list' => isset($list['data']) ? $list['data'] : []
  107. ];
  108. }
  109. /**
  110. * 成交交易笔数
  111. * @param int $type 类型:1-买单,2-卖单
  112. * @param int $bsid 承兑商用户ID
  113. * @param int $status 状态:4-成交
  114. * @return mixed
  115. */
  116. public function getCompleteCount($type = 1, $bsid = 0, $status = 4)
  117. {
  118. return (int)$this->model->where(['type' => $type, 'status' => $status, 'mark' => 1])
  119. ->where(function ($query) use ($bsid) {
  120. if ($bsid > 0) {
  121. $query->where('business_id', '=', $bsid);
  122. }
  123. })->count('id');
  124. }
  125. /**
  126. * 成交交易金额
  127. * @param int $type 类型:1-买单,2-卖单
  128. * @param int $bsid 承兑商用户ID
  129. * @param int $status 状态:4-成交
  130. * @param string $field 统计字段:total-总金额(默认),num-交易USDT数量
  131. * @return mixed
  132. */
  133. public function getCompleteTotal($type = 1, $bsid = 0, $status = 4, $field = 'total')
  134. {
  135. $total = $this->model->where(['type' => $type, 'status' => $status, 'mark' => 1])
  136. ->where(function ($query) use ($bsid) {
  137. if ($bsid > 0) {
  138. $query->where('business_id', '=', $bsid);
  139. }
  140. })->sum($field);
  141. return moneyFormat($total, 2);
  142. }
  143. /**
  144. * 今日成交交易金额
  145. * @param int $type 类型:1-买单,2-卖单
  146. * @param int $bsid 承兑商用户ID
  147. * @param int $status 状态:4-成交
  148. * @param string $field 统计字段:total-总金额(默认),num-交易USDT数量
  149. * @return mixed
  150. */
  151. public function getCompleteTotalByDay($type = 1, $bsid = 0, $status = 4, $field = 'total')
  152. {
  153. $total = $this->model->where(['type' => $type, 'status' => $status, 'mark' => 1])
  154. ->where('pay_time', '>=', strtotime(date('Y-m-d')))
  155. ->where(function ($query) use ($bsid) {
  156. if ($bsid > 0) {
  157. $query->where('business_id', '=', $bsid);
  158. }
  159. })->sum($field);
  160. return moneyFormat($total, 6);
  161. }
  162. /**
  163. * 获取某个时间段的买卖交易量比
  164. * @param int $type 状态类型:1-成交的
  165. * @param int $bsid 承兑商用户ID
  166. * @param int $time 时间/分钟,默认15分钟
  167. * @return array
  168. */
  169. public function getCountRateByTime($type = 1, $bsid = 0, $time = 15)
  170. {
  171. $where = ['mark' => 1];
  172. if ($type == 1) {
  173. $where['status'] = 4;
  174. }
  175. $buyCount = $this->model->where(['type' => 1])->where($where)
  176. ->where(function ($query) use ($bsid) {
  177. if ($bsid > 0) {
  178. $query->where('business_id', '=', $bsid);
  179. }
  180. })
  181. ->where('create_time', '>=', time() - $time * 60)
  182. ->count('id');
  183. $sellCount = $this->model->where(['type' => 2])->where($where)
  184. ->where(function ($query) use ($bsid) {
  185. if ($bsid > 0) {
  186. $query->where('business_id', '=', $bsid);
  187. }
  188. })
  189. ->where('create_time', '>=', time() - $time * 60)
  190. ->count('id');
  191. $rate = ($buyCount || $sellCount) > 0 ? moneyFormat($buyCount / ($buyCount + $sellCount)) * 100 : 0;
  192. return ['buy' => $buyCount, 'sell' => $sellCount, 'buy_rate' => $rate, 'sell_rate' => ($sellCount > 0 ? 100 - $rate : 0)];
  193. }
  194. /**
  195. * 获取未支付或处理的订单数
  196. * @param $userId
  197. * @param int $type
  198. * @return mixed
  199. */
  200. public function checkOrderNoCatch($userId, $type = 1)
  201. {
  202. return $this->model->where(['user_id' => $userId, 'type' => $type, 'mark' => 1])->whereIn('status', [1, 2])->count('id');
  203. }
  204. /**
  205. * 客户买入
  206. * @param $userId
  207. * @param $params
  208. * @return false|int|number
  209. */
  210. public function buy($userId, $params)
  211. {
  212. $num = isset($params['num']) ? floatval($params['num']) : 0;
  213. $numType = isset($params['num_type']) ? intval($params['num_type']) : 1;
  214. if ($userId <= 0) {
  215. $this->error = '1013';
  216. return false;
  217. }
  218. // 验证参数
  219. $config = ConfigService::make()->getConfigOptionByGroup(5);
  220. $tradeOpen = isset($config['trade_usdt_open']) ? $config['trade_usdt_open'] : 0;
  221. $tradeMinNum = isset($config['trade_min_num']) ? $config['trade_min_num'] : 0;
  222. $tradeMaxNum = isset($config['trade_max_num']) ? $config['trade_max_num'] : 0;
  223. $trademinMoney = isset($config['trade_min_money']) ? $config['trade_min_money'] : 0;
  224. $tradeMaxMoney = isset($config['trade_max_money']) ? $config['trade_max_money'] : 0;
  225. $tradePrice = isset($config['usdt_buy_price']) ? $config['usdt_buy_price'] : 0;
  226. $tradeLimitNum = isset($config['trade_no_catch']) ? $config['trade_no_catch'] : 0;
  227. // 是否开启交易
  228. if ($tradeOpen != 1) {
  229. $this->error = '1013';
  230. return false;
  231. }
  232. if ($tradePrice <= 0) {
  233. $this->error = '3002';
  234. return false;
  235. }
  236. // 验证数量或金额
  237. $total = 0;
  238. if ($numType == 1) {
  239. if ($num < $tradeMinNum || $num > $tradeMaxNum) {
  240. $this->error = '3003';
  241. return false;
  242. }
  243. $total = moneyFormat($num * $tradePrice, 6);
  244. } else {
  245. if ($num < $trademinMoney || $num > $tradeMaxMoney) {
  246. $this->error = '3003';
  247. return false;
  248. }
  249. $total = moneyFormat($num, 6);
  250. $num = moneyFormat($num * $tradePrice, 6);
  251. }
  252. // 用户信息
  253. $userInfo = MemberService::make()->getInfo($userId);
  254. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  255. if ($status != 1) {
  256. $this->error = '2009';
  257. return false;
  258. }
  259. // 匹配交易商家
  260. $businessInfo = \App\Services\Api\MemberService::make()->getTradeMember($num, 1, $userId);
  261. if (empty($businessInfo)) {
  262. $this->error = '3004';
  263. return false;
  264. }
  265. $noCatchOrder = $this->checkOrderNoCatch($userId, 1);
  266. if ($tradeLimitNum > 0 && $noCatchOrder >= $tradeLimitNum) {
  267. $this->error = lang(3005, ['num' => $tradeLimitNum]);
  268. return false;
  269. }
  270. $data = [
  271. 'user_id' => $userId,
  272. 'business_id' => isset($businessInfo['id']) ? $businessInfo['id'] : 0,
  273. 'order_no' => get_order_num('OT'),
  274. 'type' => 1,
  275. 'pay_type' => isset($params['pay_type']) ? floatval($params['pay_type']) : 1,
  276. 'price' => $tradePrice,
  277. 'num' => $num,
  278. 'total' => $total,
  279. 'create_time' => time(),
  280. 'update_time' => time(),
  281. 'status' => 1,
  282. 'mark' => 1,
  283. ];
  284. return $this->model->edit($data);
  285. }
  286. /**
  287. * 客户卖出
  288. * @param $userId
  289. * @param $params
  290. * @return false|int|number
  291. */
  292. public function sell($userId, $params)
  293. {
  294. $num = isset($params['num']) ? floatval($params['num']) : 0;
  295. if ($userId <= 0) {
  296. $this->error = '1013';
  297. return false;
  298. }
  299. // 验证参数
  300. $config = ConfigService::make()->getConfigOptionByGroup(5);
  301. $tradeOpen = isset($config['trade_usdt_open']) ? $config['trade_usdt_open'] : 0;
  302. $tradeMinNum = isset($config['trade_min']) ? $config['trade_min'] : 0;
  303. $tradeMaxNum = isset($config['trade_max']) ? $config['trade_max'] : 0;
  304. $tradePrice = isset($config['usdt_sell_price']) ? $config['usdt_sell_price'] : 0;
  305. $tradeLimitNum = isset($config['trade_no_catch']) ? $config['trade_no_catch'] : 0;
  306. // 是否开启交易
  307. if ($tradeOpen != 1) {
  308. $this->error = '1013';
  309. return false;
  310. }
  311. if ($tradePrice <= 0) {
  312. $this->error = '3002';
  313. return false;
  314. }
  315. // 验证数量或金额
  316. $total = moneyFormat($num * $tradePrice, 6);
  317. if ($num < $tradeMinNum || ($tradeMaxNum && $num > $tradeMaxNum)) {
  318. $this->error = '3003';
  319. return false;
  320. }
  321. // 用户信息
  322. $userInfo = MemberService::make()->getInfo($userId);
  323. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  324. $usdtNum = isset($userInfo['usdt_num']) ? $userInfo['usdt_num'] : 0;
  325. if ($status != 1) {
  326. $this->error = '2009';
  327. return false;
  328. }
  329. if ($usdtNum < $num) {
  330. $this->error = '3011';
  331. return false;
  332. }
  333. // 匹配交易商家
  334. $businessInfo = \App\Services\Api\MemberService::make()->getTradeMember($num, 2, $userId);
  335. if (empty($businessInfo)) {
  336. $this->error = '3004';
  337. return false;
  338. }
  339. // 未处理订单
  340. $noCatchOrder = $this->checkOrderNoCatch($userId, 2);
  341. if ($tradeLimitNum > 0 && $noCatchOrder >= $tradeLimitNum) {
  342. $this->error = lang(3005, ['num' => $tradeLimitNum]);
  343. return false;
  344. }
  345. // 收款方式
  346. $paymentId = isset($params['payment_id']) ? $params['payment_id'] : 0;
  347. $paymentInfo = MemberPaymentService::make()->getInfo($paymentId);
  348. if (empty($paymentInfo)) {
  349. $this->error = '3010';
  350. return false;
  351. }
  352. $paymentData = [
  353. 'payment_id' => $paymentInfo['id'],
  354. 'type' => $paymentInfo['type'],
  355. 'logo' => $paymentInfo['logo'] ? get_image_url($paymentInfo['logo']) : '',
  356. 'real_name' => $paymentInfo['real_name'],
  357. 'bank_name' => $paymentInfo['bank_name'],
  358. 'bank_card' => $paymentInfo['bank_card'],
  359. 'branch_name' => $paymentInfo['branch_name'],
  360. 'qrcode' => $paymentInfo['qrcode'] ? get_image_url($paymentInfo['qrcode']) : '',
  361. 'account' => $paymentInfo['account'],
  362. ];
  363. $data = [
  364. 'user_id' => $userId,
  365. 'business_id' => isset($businessInfo['id']) ? $businessInfo['id'] : 0,
  366. 'order_no' => get_order_num('OT'),
  367. 'type' => 2,
  368. 'pay_type' => isset($params['pay_type']) ? floatval($params['pay_type']) : 1,
  369. 'price' => $tradePrice,
  370. 'num' => $num,
  371. 'payment_id' => $paymentId,
  372. 'payment_data' => json_encode($paymentData, 256),
  373. 'total' => $total,
  374. 'create_time' => time(),
  375. 'status' => 1,
  376. 'mark' => 1,
  377. ];
  378. $this->model->startTrans();
  379. if (!$order = $this->model->edit($data)) {
  380. $this->error = '3012';
  381. $this->model->rollBack();
  382. return false;
  383. }
  384. // 扣除币
  385. if (!$this->memberModel->where(['id' => $userId])->decrement('usdt_num', $num)) {
  386. $this->error = '3013';
  387. $this->model->rollBack();
  388. return false;
  389. }
  390. // 账户明细
  391. $data = [
  392. 'order_no' => $data['order_no'],
  393. 'user_id' => $userId,
  394. 'type' => 1,
  395. 'change_type' => 2,
  396. 'num' => $num,
  397. 'total' => $total,
  398. 'create_time' => time(),
  399. 'remark' => '',
  400. 'status' => 1,
  401. 'mark' => 1,
  402. ];
  403. if (!$this->capitalModel->edit($data)) {
  404. $this->error = '3014';
  405. $this->model->rollBack();
  406. return false;
  407. }
  408. $this->model->commit();
  409. return $order;
  410. }
  411. public function catchInvalidOrder()
  412. {
  413. $overtime = ConfigService::make()->getConfigByCode('trade_order_overtime');
  414. $cancelTime = ConfigService::make()->getConfigByCode('trade_order_cancel');
  415. $catchNum = ConfigService::make()->getConfigByCode('trade_order_catch_num');
  416. $catchNum = $catchNum>0? $catchNum : 200;
  417. // 处理超时订单
  418. if ($overtime > 0) {
  419. $this->model->where(['mark' => 1])
  420. ->where('status', '<=', 2)
  421. ->where('create_time', '<=', time() - $overtime * 60)
  422. ->update(['status' => 7, 'catch_at' => time()]);
  423. }
  424. if ($cancelTime <= 0) {
  425. $this->error = '1023';
  426. return false;
  427. }
  428. $this->model->where(function ($query) use ($cancelTime) {
  429. // 已更新为超时的订单
  430. $query->where(['mark' => 1, 'status' => 7])
  431. ->where('catch_at', '<=', time() - $cancelTime * 60);
  432. })
  433. ->orWhere(function ($query) use ($cancelTime, $overtime) {
  434. $query->where('mark', '=', 1)
  435. ->where('status', '<=', 2)
  436. ->where('create_time', '<=', time() - ($cancelTime + $overtime) * 60);
  437. })
  438. ->select(['id', 'user_id', 'business_id', 'type', 'num'])
  439. ->get()
  440. ->limit(500)
  441. ->each(function ($item, $k) {
  442. //
  443. $type = isset($item['type'])? $item['type'] : 0;
  444. if($type == 2){
  445. }
  446. });
  447. }
  448. }