MemberService.php 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066
  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\Api;
  12. use App\Helpers\Jwt;
  13. use App\Models\AccountLogModel;
  14. use App\Models\BalanceLogModel;
  15. use App\Models\MemberLevelModel;
  16. use App\Models\MemberModel;
  17. use App\Services\BaseService;
  18. use App\Services\ConfigService;
  19. use App\Services\RedisService;
  20. use App\Services\ToolService;
  21. use App\Services\WalletService;
  22. use Illuminate\Support\Facades\DB;
  23. use phpqrcode\QRcode;
  24. /**
  25. * 会员-服务类
  26. * @author laravel开发员
  27. * @since 2020/11/11
  28. * @package App\Services\Api
  29. */
  30. class MemberService extends BaseService
  31. {
  32. protected static $instance;
  33. /**
  34. * 构造函数
  35. * @author laravel开发员
  36. * @since 2020/11/11
  37. */
  38. public function __construct()
  39. {
  40. $this->model = new MemberModel();
  41. }
  42. /**
  43. * 静态入口
  44. */
  45. public static function make()
  46. {
  47. if (!self::$instance) {
  48. self::$instance = new static();
  49. }
  50. return self::$instance;
  51. }
  52. /**
  53. * 登录注册
  54. * @param $walletUrl
  55. * @param string $scode
  56. * @return array|false
  57. */
  58. public function loginOrRegister($walletUrl, $scode = '')
  59. {
  60. if (empty($walletUrl)) {
  61. $this->error = 1038;
  62. return false;
  63. }
  64. $info = $this->model->with(['parent'])->where(['wallet_url' => $walletUrl, 'mark' => 1])
  65. ->select(['id', 'nickname', 'member_level', 'performance', 'code', 'usdt', 'sbt', 'profit', 'parent_id', 'wallet_url', 'wallet_token', 'recharge_url', 'bonus_rate', 'pledge_auto', 'trade_status', 'status'])
  66. ->first();
  67. $info = $info ? $info->toArray() : [];
  68. $parentInfo = isset($info['parent']) ? $info['parent'] : [];
  69. $parentWalletUrl = isset($parentInfo['wallet_url']) ? $parentInfo['wallet_url'] : '';
  70. $ip = get_client_ip();
  71. $ipData = ToolService::make()->getIpAddress($ip, '');
  72. $province = isset($ipData['regionName']) ? $ipData['regionName'] : '';
  73. $city = isset($ipData['city']) ? $ipData['city'] : '';
  74. /* TODO 注册 */
  75. if (empty($info)) {
  76. // 上级账号
  77. $parentId = 0;
  78. $parentIds = '';
  79. if ($scode) {
  80. $parentInfo = $this->model->where(['code' => $scode, 'mark' => 1])->select(['id', 'parent_ids', 'wallet_url'])->first();
  81. $parentId = isset($parentInfo['id']) ? $parentInfo['id'] : 0;
  82. $parents = isset($parentInfo['parent_ids']) ? $parentInfo['parent_ids'] : '';
  83. $parentWalletUrl = isset($parentInfo['wallet_url']) ? $parentInfo['wallet_url'] : '';
  84. if ($parentId) {
  85. $parentIds = $parents ? trim($parents, ',') . ",{$parentId}," : "{$parentId},";
  86. }
  87. }
  88. // 注册奖励
  89. $awardSbtUsdt = ConfigService::make()->getConfigByCode('register_award_sbt', 0);
  90. if ($awardSbtUsdt > 0) {
  91. $sbtPrice = PriceLogService::make()->getSbtPrice();
  92. $awardSbtNum = $sbtPrice ? round($awardSbtUsdt * 1 / $sbtPrice, 2) : 0;
  93. }
  94. DB::beginTransaction();
  95. $id = $this->model->max('id') + 1;
  96. $info = [
  97. 'nickname' => 'SBT_' . substr($walletUrl, -6, 6),
  98. 'wallet_url' => $walletUrl,
  99. 'wallet_token' => make_wallet_token($walletUrl, $id),
  100. 'avatar' => '',
  101. 'recharge_url' => '',
  102. 'member_level' => 0,
  103. 'usdt' => 0.00,
  104. 'sbt' => $awardSbtNum,
  105. 'profit' => 0.00,
  106. 'bonus_rate' => 0.00,
  107. 'performance' => 0.00,
  108. 'parent_id' => $parentId,
  109. 'parent_ids' => $parentIds,
  110. 'pledge_auto' => 1,
  111. 'code' => strtoupper(get_random_code(9, 'S', "{$id}")),
  112. 'login_ip' => $ip,
  113. 'login_region' => $province . '' . $city,
  114. 'login_time' => time(),
  115. 'create_time' => time(),
  116. 'trade_status' => 1,
  117. 'status' => 1,
  118. 'mark' => 1,
  119. ];
  120. if (!$userId = $this->model->insertGetId($info)) {
  121. DB::rollBack();
  122. $this->error = 2007;
  123. return false;
  124. }
  125. if ($awardSbtNum > 0) {
  126. $log = [
  127. 'user_id' => $userId,
  128. 'type' => 13,
  129. 'order_no' => get_order_num('RW'),
  130. 'coin_type' => 2,
  131. 'money' => $awardSbtNum,
  132. 'before_money' => 0,
  133. 'create_time' => time(),
  134. 'remark' => '注册奖励',
  135. 'action_ip' => get_client_ip(),
  136. 'status' => 1,
  137. 'mark' => 1
  138. ];
  139. if (!AccountLogModel::insertGetId($log)) {
  140. DB::rollBack();
  141. $this->error = 2007;
  142. return false;
  143. }
  144. }
  145. DB::commit();
  146. // 清除团队统计数据或列表缓存
  147. RedisService::keyDel("caches:team*");
  148. } else {
  149. $userId = $info['id'];
  150. $status = isset($info['status']) ? $info['status'] : 0;
  151. if ($status != 1) {
  152. $this->error = 2015;
  153. return false;
  154. }
  155. $updateData = [
  156. 'login_ip' => $ip,
  157. 'login_region' => $province . '' . $city,
  158. 'login_time' => time(),
  159. 'update_time' => time(),
  160. ];
  161. if ($info['wallet_token'] == '') {
  162. $updateData['wallet_token'] = make_wallet_token($walletUrl, $userId);
  163. }
  164. $this->model->where(['id' => $userId])->update($updateData);
  165. }
  166. // 获取授权TOKEN
  167. $jwt = new Jwt('jwt_wx');
  168. $token = $jwt->getToken($userId);
  169. RedisService::set("auths:info:{$userId}", $info, 6 * 3600);
  170. $this->error = 2004;
  171. return [
  172. 'token' => $token,
  173. 'info' => [
  174. 'id' => $userId,
  175. 'wallet_url' => $info['wallet_url'],
  176. 'member_level' => intval($info['member_level']),
  177. 'usdt' => round($info['usdt'], 4),
  178. 'sbt' => round($info['sbt'], 2),
  179. 'profit' => round($info['profit'], 2),
  180. 'performance' => round($info['performance'], 2),
  181. 'code' => $info['code'],
  182. 'nickname' => $info['nickname'],
  183. 'parent_id' => $info['parent_id'],
  184. 'bonus_rate' => $info['bonus_rate'],
  185. 'pledge_auto' => $info['pledge_auto'],
  186. 'parent_url' => $parentWalletUrl,
  187. ],
  188. ];
  189. }
  190. /**
  191. * 用户信息
  192. * @param int $userId 用户ID
  193. * @param int $type 返回数据类型:1-默认,2-充值,3-提现
  194. * @param false $refresh
  195. * @return array|mixed
  196. */
  197. public function getInfo(int $userId, $type = 1, $refresh = false)
  198. {
  199. $cacheKey = "caches:member:info_{$userId}_{$type}";
  200. $info = RedisService::get($cacheKey);
  201. if ($info && !$refresh) {
  202. return $info;
  203. }
  204. $info = $this->model->with(['parent'])->where(['id' => $userId, 'mark' => 1])
  205. ->select(['id', 'nickname', 'code', 'member_level', 'usdt', 'sbt', 'performance', 'profit', 'profit_total', 'pledge_profit', 'manage_profit', 'share_profit', 'pj_profit', 'global_profit', 'parent_id', 'wallet_url', 'wallet_token', 'recharge_url', 'bonus_rate', 'pledge_auto', 'trade_status', 'status'])
  206. ->first();
  207. $info = $info ? $info->toArray() : [];
  208. if (empty($info)) {
  209. $this->error = 2016;
  210. return false;
  211. }
  212. $parentInfo = isset($info['parent']) ? $info['parent'] : [];
  213. $parentWalletUrl = isset($parentInfo['wallet_url']) ? $parentInfo['wallet_url'] : '';
  214. $walletUrl = isset($info['wallet_url']) ? $info['wallet_url'] : '';
  215. $walletToken = isset($info['wallet_token']) ? $info['wallet_token'] : '';
  216. if ($type == 3 && $walletUrl && $walletToken != make_wallet_token($walletUrl, $userId)) {
  217. $info['error'] = '钱包地址已被修改';
  218. }
  219. $rechargeAddress = WalletService::make()->getWallet(1);
  220. $rechargeUrl = isset($rechargeAddress['address']) ? $rechargeAddress['address'] : '';
  221. $info = [
  222. 'id' => $userId,
  223. 'wallet_url' => $info['wallet_url'],
  224. 'member_level' => intval($info['member_level']),
  225. 'usdt' => moneyFormat($info['usdt'], 2),
  226. 'sbt' => moneyFormat($info['sbt'], 2),
  227. 'performance' => moneyFormat($info['performance'], 2),
  228. 'profit' => moneyFormat($info['profit'], 2),
  229. 'profit_total' => moneyFormat($info['profit_total'], 2),
  230. 'pledge_total' => moneyFormat($info['pledge_profit'], 2),
  231. 'share_profit' => moneyFormat($info['share_profit'], 2),
  232. 'manage_profit' => moneyFormat($info['manage_profit'], 2),
  233. 'global_profit' => moneyFormat($info['global_profit'], 2),
  234. 'pj_profit' => moneyFormat($info['pj_profit'], 2),
  235. 'code' => $info['code'],
  236. 'nickname' => $info['nickname'],
  237. 'parent_id' => $info['parent_id'],
  238. 'bonus_rate' => $info['bonus_rate'],
  239. 'pledge_auto' => $info['pledge_auto'],
  240. 'error' => isset($info['error']) ? $info['error'] : '',
  241. 'parent_url' => $parentWalletUrl,
  242. 'recharge_url' => $rechargeUrl,
  243. 'max_usdt_rate' => ConfigService::make()->getConfigByCode('usdt_withdraw_max_rate', 0),
  244. 'sbt_fee' => ConfigService::make()->getConfigByCode('profit_withdraw_sbt_fee', 0),
  245. 'recharge_min' => ConfigService::make()->getConfigByCode('recharge_min_money', 0.1),
  246. 'withdraw_min' => ConfigService::make()->getConfigByCode('withdraw_min_money', 0),
  247. ];
  248. if ($type == 1) {
  249. $chainTotal = BalanceLogService::make()->getCountByType($userId, 1);
  250. $ptTotal = AccountLogService::make()->getCountByType($userId, 5, 1);
  251. $info['recharge_total'] = moneyFormat($chainTotal + $ptTotal, 2);
  252. $chainTotal = BalanceLogService::make()->getCountByType($userId, 2, 0, 0);
  253. $ptTotal = AccountLogService::make()->getCountByType($userId, 6, 1);
  254. $info['withdraw_total'] = moneyFormat($chainTotal + $ptTotal, 2);
  255. }
  256. RedisService::set($cacheKey, $info, rand(5, 10));
  257. return $info;
  258. }
  259. /**
  260. * 获取级数据
  261. * @param $levelId
  262. * @param $type 类型:1-当前等级数据,2-下一等级数据
  263. * @return array|mixed
  264. */
  265. public function getLevelData($levelId, $type = 1)
  266. {
  267. $cacheKey = "caches:member:level_{$levelId}_{$type}";
  268. $info = RedisService::get($cacheKey);
  269. if ($info) {
  270. return $info;
  271. }
  272. $data = MemberLevelModel::where(function ($query) use ($type, $levelId) {
  273. if ($type == 2) {
  274. $query->where('id', '>', $levelId);
  275. } else {
  276. $query->where('id', $levelId);
  277. }
  278. })
  279. ->where(['status' => 1, 'mark' => 1])
  280. ->select(['id', 'name', 'upgrade_usdt', 'bonus_rate', 'weighting_rate'])
  281. ->orderBy('sort', 'asc')
  282. ->orderBy('id', 'asc')
  283. ->first();
  284. $data = $data ? $data->toArray() : [];
  285. if ($data) {
  286. RedisService::set($cacheKey, $data, rand(3600, 7200));
  287. }
  288. return $data;
  289. }
  290. /**
  291. * 设置分红比例
  292. * @param int $userId 用户ID
  293. * @param array $params 参数,user_id-设置用户ID(必选),bonus_rate-比例
  294. * @return bool
  295. */
  296. public function setBonus(int $userId, array $params)
  297. {
  298. // 参数验证
  299. $uid = isset($params['user_id']) ? intval($params['user_id']) : 0;
  300. $bonusRate = isset($params['bonus_rate']) && $params['bonus_rate'] > 0 ? floatval($params['bonus_rate']) : 0;
  301. if ($uid <= 0) {
  302. $this->error = 2014;
  303. return false;
  304. }
  305. if ($bonusRate < 0 || $bonusRate >= 100) {
  306. $this->error = 1022;
  307. return false;
  308. }
  309. $info = $this->model->where(['id' => $userId, 'mark' => 1])->first();
  310. if (empty($info)) {
  311. $this->error = 2016;
  312. return false;
  313. }
  314. // 账号状态
  315. $status = isset($info['status']) ? $info['status'] : 0;
  316. if ($status != 1) {
  317. $this->error = 2015;
  318. return false;
  319. }
  320. // 设置用户
  321. $userInfo = $this->model->where(['id' => $uid, 'status' => 1, 'mark' => 1])
  322. ->select(['id', 'parent_id', 'parent_ids', 'bonus_rate'])
  323. ->first();
  324. if (empty($userInfo)) {
  325. $this->error = 1042;
  326. return false;
  327. }
  328. // 上级用户校验
  329. $parentId = isset($userInfo['parent_id']) ? $userInfo['parent_id'] : 0;
  330. $parentIds = isset($userInfo['parent_ids']) ? $userInfo['parent_ids'] : '';
  331. if ($parentId != $userId) {
  332. $this->error = 1043;
  333. return false;
  334. }
  335. // 最大设置比例
  336. $maxBonusRate = $this->getUpBonusRate($uid, $parentIds);
  337. if ($maxBonusRate > 0 && $bonusRate > $maxBonusRate) {
  338. $this->errorData = ['rate' => $maxBonusRate];
  339. $this->error = 1043;
  340. return false;
  341. }
  342. // 更新数据
  343. $data = [
  344. 'bonus_rate' => floatval($bonusRate),
  345. 'update_time' => time()
  346. ];
  347. if (!$this->model->where(['id' => $uid])->update($data)) {
  348. $this->error = 1020;
  349. return false;
  350. }
  351. $this->error = 1019;
  352. return true;
  353. }
  354. /**
  355. * 获取上级团队设置的最近的比例
  356. * @param $userId
  357. * @param $parentIds
  358. * @return false|int|mixed
  359. */
  360. public function getUpBonusRate($userId, $parentIds)
  361. {
  362. $cacheKey = "caches:member:upRate_{$userId}";
  363. $data = RedisService::get($cacheKey);
  364. if ($data) {
  365. return isset($data['bonus_rate']) ? $data['bonus_rate'] : 0;
  366. }
  367. $parentIds = $parentIds ? explode(',', $parentIds) : [];
  368. $parentIds = array_filter($parentIds);
  369. krsort($parentIds);
  370. if (empty($parentIds) || !is_array($parentIds)) {
  371. return 0;
  372. }
  373. $data = $this->model->whereIn('id', $parentIds)
  374. ->where('bonus_rate', '>', 0)
  375. ->where(['mark' => 1])
  376. ->select(['id', 'bonus_rate'])
  377. ->orderByRaw('FIELD(id, "' . implode(',', $parentIds) . '")')
  378. ->first();
  379. $data = $data ? $data->toArray() : [];
  380. if ($data) {
  381. RedisService::set($cacheKey, $data, rand(3, 5));
  382. }
  383. return isset($data['bonus_rate']) ? $data['bonus_rate'] : 0;
  384. }
  385. /**
  386. * 设置自动质押状态
  387. * @param int $userId 用户ID
  388. * @param array $params 参数,status-状态(1-开启,0-关闭,必选)
  389. * @return bool
  390. */
  391. public function setPledge(int $userId, array $params)
  392. {
  393. // 参数验证
  394. $pledgeStatus = isset($params['status']) ? intval($params['status']) : 0;
  395. if (!in_array($pledgeStatus, [0, 1])) {
  396. $this->error = 2014;
  397. return false;
  398. }
  399. // 关闭限制验证
  400. $cacheKey = "caches:pledge:limitClose_{$userId}";
  401. if ($pledgeStatus == 0 && RedisService::get($cacheKey)) {
  402. $this->error = 2031;
  403. return false;
  404. }
  405. // 账号信息
  406. $info = $this->model->where(['id' => $userId, 'mark' => 1])->select(['id', 'pledge_auto', 'status'])->first();
  407. if (empty($info)) {
  408. $this->error = 2016;
  409. return false;
  410. }
  411. // 账号状态
  412. $status = isset($info['status']) ? $info['status'] : 0;
  413. if ($status != 1) {
  414. $this->error = 2015;
  415. return false;
  416. }
  417. // 质押过,且已经退本过才可关闭
  418. if ($pledgeStatus == 0 && !PledgeOrderService::make()->checkPledge($userId)) {
  419. $this->error = 2030;
  420. return false;
  421. }
  422. // 更新
  423. $data = ['pledge_auto' => $pledgeStatus, 'update_time' => time()];
  424. if (!$this->model->where(['id' => $userId])->update($data)) {
  425. $this->error = 1020;
  426. return false;
  427. }
  428. // 限制关闭次数
  429. if ($pledgeStatus == 0) {
  430. RedisService::set($cacheKey, date('Y-m-d H:i:s'), 30);
  431. }
  432. $this->error = 1019;
  433. return true;
  434. }
  435. /**
  436. * 保存资料
  437. * @param int $userId 用户ID
  438. * @param $params 参数
  439. * @return bool
  440. */
  441. public function setProfile(int $userId, $params)
  442. {
  443. $info = $this->model->where(['id' => $userId, 'mark' => 1])->first();
  444. if (empty($info)) {
  445. $this->error = 2016;
  446. return false;
  447. }
  448. $data = [
  449. 'update_time' => time()
  450. ];
  451. if (isset($params['nickname']) && $params['nickname']) {
  452. $data['nickname'] = trim($params['nickname']);
  453. }
  454. // 头像
  455. // 更新
  456. if (!$this->model->where(['id' => $userId])->update($data)) {
  457. $this->error = 1009;
  458. return false;
  459. }
  460. $this->error = 1008;
  461. return true;
  462. }
  463. /**
  464. * 生成普通参数二维码
  465. * @param $str 参数
  466. * @param bool $refresh 是否重新生成
  467. * @return bool
  468. */
  469. public function makeQrcode($str, $dir='qrcode', $refresh = false, $size = 4, $margin = 2, $level = 2)
  470. {
  471. $basePath = base_path() . '/public';
  472. $qrFile = "/images/{$dir}/";
  473. if (!is_dir($basePath . '/uploads' . $qrFile)) {
  474. @mkdir($basePath . '/uploads' . $qrFile, 0755, true);
  475. }
  476. $key = date('Ymd') . strtoupper(md5($str . '_' . $size . $margin . $level));
  477. $qrFile = $qrFile . "C_{$key}.png";
  478. $cacheKey = "caches:qrcodes:member_" . $key;
  479. if (RedisService::get($cacheKey) && is_file($basePath . '/uploads' . $qrFile) && !$refresh) {
  480. return $qrFile;
  481. }
  482. QRcode::png($str, $basePath . '/uploads' . $qrFile, $level, $size, $margin);
  483. if (!file_exists($basePath . '/uploads' . $qrFile)) {
  484. return false;
  485. }
  486. RedisService::set($cacheKey, ['str' => $str, 'qrcode' => $qrFile, 'date' => date('Y-m-d H:i:s')], 7 * 24 * 3600);
  487. return $qrFile;
  488. }
  489. /**
  490. * 提现
  491. * @param $userId 提现用户ID
  492. * @param $params 提现参数:money-金额(必选)、coin_type-账户类型/币种(必选)
  493. * @return array|false|mixed
  494. */
  495. public function withdraw($userId, $params)
  496. {
  497. $money = isset($params['money']) ? floatval($params['money']) : 0;
  498. $coinType = isset($params['coin_type']) ? intval($params['coin_type']) : 1;
  499. if ($money <= 0) {
  500. $this->error = 2025;
  501. return false;
  502. }
  503. // 锁
  504. $coinType = $coinType == 1 ? 1 : 2;
  505. $cacheKey = "caches:withdraw:{$userId}_{$coinType}";
  506. if (RedisService::get($cacheKey . '_lock')) {
  507. return false;
  508. }
  509. $info = $this->model->where(['id' => $userId, 'mark' => 1])->first();
  510. if (empty($info)) {
  511. $this->error = 2016;
  512. return false;
  513. }
  514. $status = isset($info['status']) ? $info['status'] : 0;
  515. $tradeStatus = isset($info['trade_status']) ? $info['trade_status'] : 0;
  516. $userUsdt = isset($info['usdt']) ? floatval($info['usdt']) : 0;
  517. $userProfit = isset($info['profit']) ? floatval($info['profit']) : 0;
  518. $userSbt = isset($info['sbt']) ? floatval($info['sbt']) : 0;
  519. if ($status != 1) {
  520. $this->error = 2015; // 冻结
  521. return false;
  522. }
  523. if (in_array($tradeStatus, [2, 3])) {
  524. $this->error = intval("202{$tradeStatus}");
  525. return false;
  526. }
  527. // 可提金额或手续费验证
  528. try {
  529. DB::beginTransaction();
  530. RedisService::set($cacheKey . '_lock', date('Y-m-d H:i:s'), rand(3,5));
  531. if ($coinType == 1) {
  532. $maxUsdtRate = ConfigService::make()->getConfigByCode('usdt_withdraw_max_rate', 0);
  533. $withdrawTotal = BalanceLogService::make()->getCountByType($userId, 2, 1, 0);
  534. $maxWithdrawMoney = ($withdrawTotal + $userUsdt);
  535. $maxWithdrawMoney = $maxUsdtRate > 0 && $maxUsdtRate < 100 ? moneyFormat($maxWithdrawMoney * $maxUsdtRate / 100, 2) : $maxWithdrawMoney;
  536. if (($withdrawTotal + floatval($money)) >= $maxWithdrawMoney) {
  537. DB::rollBack();
  538. $this->error = 2026; // 可提金额超出
  539. $this->errorData = ['money' => moneyFormat($maxWithdrawMoney - $withdrawTotal, 2)];
  540. RedisService::clear($cacheKey . '_lock');
  541. return false;
  542. }
  543. // 提现处理
  544. $updateData = ['usdt' => DB::raw("usdt - {$money}"), 'update_time' => time()];
  545. if (!$this->model->where(['id' => $userId])->update($updateData)) {
  546. DB::rollBack();
  547. $this->error = 2033; // 提现处理失败
  548. RedisService::clear($cacheKey . '_lock');
  549. return false;
  550. }
  551. // 账单
  552. $log = [
  553. 'user_id' => $userId,
  554. 'order_no' => get_order_num('SW'),
  555. 'type' => 2,
  556. 'user_type' => 1,
  557. 'coin_type' => 1,
  558. 'money' => $money,
  559. 'actual_money' => $money,
  560. 'fee' => 0,
  561. 'pay_type' => 10,
  562. 'pay_status' => 10,
  563. 'wallet_url' => $info['wallet_url'],
  564. 'pt_wallet_url' => '',
  565. 'date' => date('Y-m-d'),
  566. 'create_time' => time(),
  567. 'audit_remark' => '',
  568. 'status' => 1,
  569. 'mark' => 1,
  570. ];
  571. if (!BalanceLogModel::insertGetId($log)) {
  572. DB::rollBack();
  573. $this->error = 2033;
  574. RedisService::clear($cacheKey . '_lock');
  575. return false;
  576. }
  577. // USDT余额账单
  578. $data = [
  579. 'user_id' => $userId,
  580. 'order_no' => $log['order_no'],
  581. 'type' => 4,
  582. 'user_type' => 1,
  583. 'coin_type' => 1,
  584. 'money' => -$money,
  585. 'before_money' => $userUsdt,
  586. 'create_time' => time(),
  587. 'action_ip' => get_client_ip(),
  588. 'remark' => '余额提现',
  589. 'status' => 1,
  590. 'mark' => 1,
  591. ];
  592. if (!AccountLogModel::insertGetId($data)) {
  593. DB::rollBack();
  594. $this->error = 2033;
  595. RedisService::clear($cacheKey . '_lock');
  596. return false;
  597. }
  598. // 成功
  599. DB::commit();
  600. return $this->getInfo($userId, 3, true);
  601. } // 收益提现
  602. else {
  603. $sbtUsdtFee = ConfigService::make()->getConfigByCode('profit_withdraw_sbt_fee', 0);
  604. $sbtPrice = PriceLogService::make()->getSbtPrice();
  605. $sbtFee = moneyFormat(floatval($sbtUsdtFee) / $sbtPrice, 2);
  606. if ($sbtFee > $userSbt) {
  607. DB::rollBack();
  608. $this->error = 2032; // 手续费不足
  609. $this->errorData = ['money' => $sbtFee];
  610. RedisService::clear($cacheKey . '_lock');
  611. return false;
  612. }
  613. // 余额是否足
  614. if ($money > $userProfit) {
  615. DB::rollBack();
  616. $this->error = 2026; // 手续费不足
  617. $this->errorData = ['money' => $userProfit];
  618. RedisService::clear($cacheKey . '_lock');
  619. return false;
  620. }
  621. // 提现处理
  622. $updateData = ['profit' => DB::raw("profit - {$money}"), 'sbt' => DB::raw("sbt - {$sbtFee}"), 'update_time' => time()];
  623. if (!$this->model->where(['id' => $userId])->update($updateData)) {
  624. DB::rollBack();
  625. $this->error = 2033; // 提现处理失败
  626. RedisService::clear($cacheKey . '_lock');
  627. return false;
  628. }
  629. // 账单
  630. $log = [
  631. 'user_id' => $userId,
  632. 'order_no' => get_order_num('SW'),
  633. 'type' => 2,
  634. 'user_type' => 1,
  635. 'coin_type' => 2,
  636. 'money' => $money,
  637. 'actual_money' => $money,
  638. 'fee' => $sbtFee,
  639. 'fee_usdt' => $sbtUsdtFee,
  640. 'pay_type' => 10,
  641. 'pay_status' => 10,
  642. 'wallet_url' => $info['wallet_url'],
  643. 'pt_wallet_url' => '',
  644. 'date' => date('Y-m-d'),
  645. 'create_time' => time(),
  646. 'audit_remark' => '',
  647. 'status' => 1,
  648. 'mark' => 1,
  649. ];
  650. if (!BalanceLogModel::insertGetId($log)) {
  651. DB::rollBack();
  652. $this->error = 2033;
  653. RedisService::clear($cacheKey . '_lock');
  654. return false;
  655. }
  656. // 收益账单
  657. $data = [
  658. 'user_id' => $userId,
  659. 'order_no' => $log['order_no'],
  660. 'type' => 4,
  661. 'user_type' => 1,
  662. 'coin_type' => 3,
  663. 'money' => -$money,
  664. 'before_money' => $userProfit,
  665. 'create_time' => time(),
  666. 'action_ip' => get_client_ip(),
  667. 'remark' => '收益提现',
  668. 'status' => 1,
  669. 'mark' => 1,
  670. ];
  671. if (!AccountLogModel::insertGetId($data)) {
  672. DB::rollBack();
  673. $this->error = 2033;
  674. RedisService::clear($cacheKey . '_lock');
  675. return false;
  676. }
  677. // 手续费账单
  678. if ($sbtFee > 0) {
  679. $data = [
  680. 'user_id' => $userId,
  681. 'order_no' => $log['order_no'],
  682. 'type' => 4,
  683. 'user_type' => 1,
  684. 'coin_type' => 2,
  685. 'money' => -$sbtFee,
  686. 'before_money' => $userSbt,
  687. 'create_time' => time(),
  688. 'action_ip' => get_client_ip(),
  689. 'remark' => '提现手续费',
  690. 'status' => 1,
  691. 'mark' => 1,
  692. ];
  693. if (!AccountLogModel::insertGetId($data)) {
  694. DB::rollBack();
  695. $this->error = 2033;
  696. RedisService::clear($cacheKey . '_lock');
  697. return false;
  698. }
  699. }
  700. // 成功
  701. DB::commit();
  702. RedisService::keyDel("caches:balanceLog:total*");
  703. RedisService::clear($cacheKey . '_lock');
  704. return $this->getInfo($userId, 3, true);
  705. }
  706. } catch (\Exception $exception) {
  707. DB::rollBack();
  708. $this->errorData = ['error' => $exception->getMessage()];
  709. RedisService::clear($cacheKey . '_lock');
  710. $this->error = 2028;
  711. return false;
  712. }
  713. }
  714. /**
  715. * 闪兑
  716. * @param $userId 用户
  717. * @param $params 参数:money-闪兑金额
  718. * @return array|false|mixed
  719. */
  720. public function exchange($userId, $params)
  721. {
  722. $money = isset($params['money']) ? floatval($params['money']) : 0;
  723. $coinType = 2;
  724. if ($money <= 0) {
  725. $this->error = 2101;
  726. return false;
  727. }
  728. $cacheKey = "caches:exchange:{$userId}_{$coinType}";
  729. if (RedisService::get($cacheKey . '_lock')) {
  730. return false;
  731. }
  732. $info = $this->model->where(['id' => $userId, 'mark' => 1])->first();
  733. if (empty($info)) {
  734. $this->error = 2016;
  735. return false;
  736. }
  737. $status = isset($info['status']) ? $info['status'] : 0;
  738. $userProfit = isset($info['profit']) ? floatval($info['profit']) : 0;
  739. $userSbt = isset($info['sbt']) ? floatval($info['sbt']) : 0;
  740. $userUsdt = isset($info['usdt']) ? floatval($info['usdt']) : 0;
  741. if ($status != 1) {
  742. $this->error = 2015; // 冻结
  743. return false;
  744. }
  745. // 闪兑验证
  746. $sbtLimit = ConfigService::make()->getConfigByCode('sbt_exchange_limit', 100);
  747. $sbtPrice = PriceLogService::make()->getSbtPrice();
  748. $sbtLimit = round($sbtLimit/$sbtPrice, 2);
  749. $sbtLimit = $sbtLimit>0? $sbtLimit : 0;
  750. if($sbtLimit>0 && $sbtLimit < $userSbt){
  751. $this->error = lang(2102,['money'=> $sbtLimit]);
  752. return false;
  753. }
  754. // 可提金额或手续费验证
  755. try {
  756. DB::beginTransaction();
  757. RedisService::set($cacheKey . '_lock',date('Y-m-d H:i:s'), rand(3,5));
  758. // TODO SBT 闪兑 USDT
  759. if ($coinType == 2) {
  760. // 手续费
  761. $exchangeFeeRate = ConfigService::make()->getConfigByCode('exchange_fee_rate', 0);
  762. $exchangeFeeRate = $exchangeFeeRate>0 && $exchangeFeeRate<100? floatval($exchangeFeeRate) : 0;
  763. // 闪兑金额
  764. $sbtUsdt = moneyFormat($money * $sbtPrice, 2); // 闪兑USDT金额
  765. $feeUsdt = round($sbtUsdt * $exchangeFeeRate/100, 2);
  766. $actualUsdt = moneyFormat($sbtUsdt - $feeUsdt, 2);
  767. // 闪兑入账收益账户处理
  768. $updateData = [
  769. 'profit' => DB::raw("profit + {$actualUsdt}"),
  770. 'sbt' => DB::raw("sbt - {$money}"),
  771. 'update_time' => time()
  772. ];
  773. if (!$this->model->where(['id' => $userId])->update($updateData)) {
  774. DB::rollBack();
  775. $this->error = 2103;
  776. RedisService::clear($cacheKey . '_lock');
  777. return false;
  778. }
  779. // SBT扣除账单
  780. $orderNo = get_order_num('SE');
  781. $data = [
  782. 'user_id' => $userId,
  783. 'order_no' => $orderNo,
  784. 'type' => 2,
  785. 'user_type' => 1,
  786. 'coin_type' => 2,
  787. 'money' => -$money,
  788. 'before_money' => $userSbt,
  789. 'create_time' => time(),
  790. 'action_ip' => get_client_ip(),
  791. 'remark' => 'SBT闪兑',
  792. 'status' => 1,
  793. 'mark' => 1,
  794. ];
  795. if (!AccountLogModel::insertGetId($data)) {
  796. DB::rollBack();
  797. $this->error = 2103;
  798. RedisService::clear($cacheKey . '_lock');
  799. return false;
  800. }
  801. // 到账USDT收益账单
  802. $data = [
  803. 'user_id' => $userId,
  804. 'order_no' => $orderNo,
  805. 'type' => 2,
  806. 'user_type' => 1,
  807. 'coin_type' => 3,
  808. 'money' => $actualUsdt,
  809. 'before_money' => $userProfit,
  810. 'create_time' => time(),
  811. 'action_ip' => get_client_ip(),
  812. 'remark' => 'SBT闪兑到账',
  813. 'status' => 1,
  814. 'mark' => 1,
  815. ];
  816. if (!AccountLogModel::insertGetId($data)) {
  817. DB::rollBack();
  818. $this->error = 2103;
  819. RedisService::clear($cacheKey . '_lock');
  820. return false;
  821. }
  822. // 闪兑手续费账单
  823. $data = [
  824. 'user_id' => $userId,
  825. 'order_no' => $orderNo,
  826. 'type' => 18,
  827. 'user_type' => 1,
  828. 'coin_type' => 3,
  829. 'money' => $feeUsdt,
  830. 'before_money' => moneyFormat($userProfit + $actualUsdt,2),
  831. 'create_time' => time(),
  832. 'action_ip' => get_client_ip(),
  833. 'remark' => 'SBT闪兑手续费',
  834. 'status' => 1,
  835. 'mark' => 1,
  836. ];
  837. if (!AccountLogModel::insertGetId($data)) {
  838. DB::rollBack();
  839. $this->error = 2103;
  840. RedisService::clear($cacheKey . '_lock');
  841. return false;
  842. }
  843. // 成功
  844. DB::commit();
  845. $this->error = 2105;
  846. return $this->getInfo($userId, 3, true);
  847. }else{
  848. DB::rollBack();
  849. $this->error = 1031;
  850. RedisService::clear($cacheKey . '_lock');
  851. return false;
  852. }
  853. } catch (\Exception $exception) {
  854. DB::rollBack();
  855. $this->errorData = ['error' => $exception->getMessage()];
  856. RedisService::clear($cacheKey . '_lock');
  857. $this->error = 2104;
  858. return false;
  859. }
  860. }
  861. /**
  862. * 更新用户等级
  863. * @param $userId 需要更新等级用户ID
  864. */
  865. public function upgradeUpdate($userId)
  866. {
  867. $cacheKey = "caches:member:levelLock_{$userId}";
  868. if (RedisService::get($cacheKey)) {
  869. $this->error = lang(4303, ['uid' => $userId]);
  870. return false;
  871. }
  872. RedisService::set($cacheKey, date('Y-m-d H:i:s'), rand(5, 10));
  873. $userInfo = $this->model->where(['id' => $userId, 'mark' => 1])
  874. ->select(['id', 'usdt', 'member_level', 'performance','upgrade_status', 'upgrade_at', 'status'])
  875. ->first();
  876. if (empty($userInfo)) {
  877. RedisService::clear($cacheKey);
  878. $this->error = lang(4301, ['uid' => $userId]);
  879. return false;
  880. }
  881. $memberLevel = isset($userInfo['member_level']) ? $userInfo['member_level'] : 0; // 个人等级
  882. $performance = isset($userInfo['performance']) ? $userInfo['performance'] : 0; // 个人业绩
  883. $upgradeStatus = isset($userInfo['upgrade_status']) ? $userInfo['upgrade_status'] : 0; // 升级方式
  884. $teamPerformance = TeamService::make()->getTeamPerformanceByType($userId, 2, true);
  885. $teamPerformance = round($teamPerformance + $performance, 2);
  886. // 等级条件
  887. $nextLevel = MemberLevelModel::where('upgrade_usdt', '<=', $teamPerformance)
  888. ->where(['status' => 1, 'mark' => 1])
  889. ->orderBy('sort', 'desc')
  890. ->orderBy('id', 'desc')
  891. ->value('id');
  892. $nextLevel = $nextLevel>0? intval($nextLevel) : 0;
  893. // 是否只升不降
  894. if ($$upgradeStatus==2 && $nextLevel<=$memberLevel) {
  895. RedisService::clear($cacheKey);
  896. $this->error = lang(4302, ['uid' => $userId]);
  897. return false;
  898. }
  899. // 更新等级
  900. if (!$this->model->where(['id' => $userId])->update(['member_level' => $nextLevel, 'old_level' => $memberLevel,'upgrade_at'=>date('Y-m-d H:i:s'), 'update_time' => time()])) {
  901. RedisService::clear($cacheKey);
  902. $this->error = lang(4302, ['uid' => $userId, 'level' => $nextLevel]);
  903. return false;
  904. }
  905. $this->error = lang(4302, ['uid' => $userId, 'level' => $nextLevel, 'old' => $memberLevel]);
  906. RedisService::set($cacheKey, ['level' => $nextLevel, 'old' => $memberLevel, 'date' => date('Y-m-d H:i:s')], rand(30, 60));
  907. return ['msg' => '更新成功', 'uid' => $userId, 'level' => $nextLevel, 'old' => $memberLevel];
  908. }
  909. /**
  910. * 获取可质押用户列表(按批次数量获取)
  911. * @return mixed
  912. */
  913. public function pledgeUserList()
  914. {
  915. try {
  916. $limit = ConfigService::make()->getConfigByCode('pledge_user_count', 500);
  917. $limit = $limit > 0 ? $limit : 500;
  918. $pledgeUsdt = ConfigService::make()->getConfigByCode('pledge_money', 500);
  919. $pledgeUsdt = $pledgeUsdt > 0 ? $pledgeUsdt : 500;
  920. $sbtPrice = PriceLogService::make()->getSbtPrice();
  921. $sbtUsdtFee = ConfigService::make()->getConfigByCode('pledge_sbt_usdt_fee', 0);
  922. $sbtUsdtFee = $sbtUsdtFee > 0 ? floatval($sbtUsdtFee) : 0;
  923. $sbtFee = $sbtUsdtFee && $sbtPrice > 0 ? moneyFormat($sbtUsdtFee / $sbtPrice, 2) : 0;
  924. $datas = $this->model->from('member as a')
  925. ->leftJoin('pledge_orders as b', 'b.user_id', '=', 'a.id')
  926. ->where('a.usdt', '>=', $pledgeUsdt)
  927. ->where('a.sbt', '>=', $sbtFee)
  928. ->where(function($query){
  929. $query->where('b.id', '<=', 0)->orWhere('a.pledge_count', '<=', 0);
  930. })
  931. ->where(['a.pledge_auto' => 1, 'a.status' => 1, 'a.mark' => 1])
  932. ->select(['a.id', 'a.pledge_auto', 'a.usdt', 'a.sbt', 'a.profit', 'a.trade_status','a.settle_status','a.status', 'a.parent_ids', 'b.id as pledge_id'])
  933. ->limit($limit)
  934. ->orderByRaw('rand()')
  935. ->orderBy('a.id', 'asc')
  936. ->get();
  937. return $datas?$datas->toArray() : [];
  938. } catch (\Exception $exception) {
  939. $this->error = $exception->getMessage();
  940. return false;
  941. }
  942. }
  943. /**
  944. * 获取需要更新等级用户列表(更新等级时间超出当前时间则需要更新)
  945. * @return mixed
  946. */
  947. public function getUpgradeUserList()
  948. {
  949. try {
  950. $limit = ConfigService::make()->getConfigByCode('upgrade_user_count', 500);
  951. $limit = $limit > 0 ? $limit : 500;
  952. $datas = $this->model->where('upgrade_at', '>', date('Y-m-d H:i:s'))
  953. ->where(['status' => 1, 'mark' => 1])
  954. ->select(['id', 'pledge_auto', 'usdt', 'sbt', 'profit', 'trade_status', 'parent_ids'])
  955. ->limit($limit)
  956. ->orderByRaw('rand()')
  957. ->orderBy('id', 'asc')
  958. ->get();
  959. return $datas?$datas->toArray() : [];
  960. } catch (\Exception $exception) {
  961. $this->error = $exception->getMessage();
  962. return false;
  963. }
  964. }
  965. }