MemberService.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  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()->checkPledgeRefund($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'), 3600);
  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. if ($coinType == 1) {
  531. $maxUsdtRate = ConfigService::make()->getConfigByCode('usdt_withdraw_max_rate', 0);
  532. $withdrawTotal = BalanceLogService::make()->getCountByType($userId, 2, 1, 0);
  533. $maxWithdrawMoney = ($withdrawTotal + $userUsdt);
  534. $maxWithdrawMoney = $maxUsdtRate > 0 && $maxUsdtRate < 100 ? moneyFormat($maxWithdrawMoney * $maxUsdtRate / 100, 2) : $maxWithdrawMoney;
  535. if (($withdrawTotal + floatval($money)) >= $maxWithdrawMoney) {
  536. DB::rollBack();
  537. $this->error = 2026; // 可提金额超出
  538. $this->errorData = ['money' => moneyFormat($maxWithdrawMoney - $withdrawTotal, 2)];
  539. return false;
  540. }
  541. // 提现处理
  542. $updateData = ['usdt' => DB::raw("usdt - {$money}"), 'update_time' => time()];
  543. if (!$this->model->where(['id' => $userId])->update($updateData)) {
  544. DB::rollBack();
  545. $this->error = 2033; // 提现处理失败
  546. return false;
  547. }
  548. // 账单
  549. $log = [
  550. 'user_id' => $userId,
  551. 'order_no' => get_order_num('SW'),
  552. 'type' => 2,
  553. 'user_type' => 1,
  554. 'coin_type' => 1,
  555. 'money' => $money,
  556. 'actual_money' => $money,
  557. 'fee' => 0,
  558. 'pay_type' => 10,
  559. 'pay_status' => 10,
  560. 'wallet_url' => $info['wallet_url'],
  561. 'pt_wallet_url' => '',
  562. 'date' => date('Y-m-d'),
  563. 'create_time' => time(),
  564. 'audit_remark' => '',
  565. 'status' => 1,
  566. 'mark' => 1,
  567. ];
  568. if (!BalanceLogModel::insertGetId($log)) {
  569. DB::rollBack();
  570. $this->error = 2033;
  571. return false;
  572. }
  573. // USDT余额账单
  574. $data = [
  575. 'user_id' => $userId,
  576. 'order_no' => $log['order_no'],
  577. 'type' => 4,
  578. 'user_type' => 1,
  579. 'coin_type' => 1,
  580. 'money' => -$money,
  581. 'before_money' => $userUsdt,
  582. 'create_time' => time(),
  583. 'action_ip' => get_client_ip(),
  584. 'remark' => '余额提现',
  585. 'status' => 1,
  586. 'mark' => 1,
  587. ];
  588. if (!AccountLogModel::insertGetId($data)) {
  589. DB::rollBack();
  590. $this->error = 2033;
  591. return false;
  592. }
  593. // 成功
  594. DB::commit();
  595. return $this->getInfo($userId, 3, true);
  596. } // 收益提现
  597. else {
  598. $sbtUsdtFee = ConfigService::make()->getConfigByCode('profit_withdraw_sbt_fee', 0);
  599. $sbtPrice = PriceLogService::make()->getSbtPrice();
  600. $sbtFee = moneyFormat(floatval($sbtUsdtFee) / $sbtPrice, 2);
  601. if ($sbtFee > $userSbt) {
  602. DB::rollBack();
  603. $this->error = 2032; // 手续费不足
  604. $this->errorData = ['money' => $sbtFee];
  605. return false;
  606. }
  607. // 余额是否足
  608. if ($money > $userProfit) {
  609. DB::rollBack();
  610. $this->error = 2026; // 手续费不足
  611. $this->errorData = ['money' => $userProfit];
  612. return false;
  613. }
  614. // 提现处理
  615. $updateData = ['profit' => DB::raw("profit - {$money}"), 'sbt' => DB::raw("sbt - {$sbtFee}"), 'update_time' => time()];
  616. if (!$this->model->where(['id' => $userId])->update($updateData)) {
  617. DB::rollBack();
  618. $this->error = 2033; // 提现处理失败
  619. return false;
  620. }
  621. // 账单
  622. $log = [
  623. 'user_id' => $userId,
  624. 'order_no' => get_order_num('SW'),
  625. 'type' => 2,
  626. 'user_type' => 1,
  627. 'coin_type' => 2,
  628. 'money' => $money,
  629. 'actual_money' => $money,
  630. 'fee' => $sbtFee,
  631. 'fee_usdt' => $sbtUsdtFee,
  632. 'pay_type' => 10,
  633. 'pay_status' => 10,
  634. 'wallet_url' => $info['wallet_url'],
  635. 'pt_wallet_url' => '',
  636. 'date' => date('Y-m-d'),
  637. 'create_time' => time(),
  638. 'audit_remark' => '',
  639. 'status' => 1,
  640. 'mark' => 1,
  641. ];
  642. if (!BalanceLogModel::insertGetId($log)) {
  643. DB::rollBack();
  644. $this->error = 2033;
  645. return false;
  646. }
  647. // 收益账单
  648. $data = [
  649. 'user_id' => $userId,
  650. 'order_no' => $log['order_no'],
  651. 'type' => 4,
  652. 'user_type' => 1,
  653. 'coin_type' => 3,
  654. 'money' => -$money,
  655. 'before_money' => $userProfit,
  656. 'create_time' => time(),
  657. 'action_ip' => get_client_ip(),
  658. 'remark' => '收益提现',
  659. 'status' => 1,
  660. 'mark' => 1,
  661. ];
  662. if (!AccountLogModel::insertGetId($data)) {
  663. DB::rollBack();
  664. $this->error = 2033;
  665. return false;
  666. }
  667. // 手续费账单
  668. if ($sbtFee > 0) {
  669. $data = [
  670. 'user_id' => $userId,
  671. 'order_no' => $log['order_no'],
  672. 'type' => 4,
  673. 'user_type' => 1,
  674. 'coin_type' => 2,
  675. 'money' => -$sbtFee,
  676. 'before_money' => $userSbt,
  677. 'create_time' => time(),
  678. 'action_ip' => get_client_ip(),
  679. 'remark' => '提现手续费',
  680. 'status' => 1,
  681. 'mark' => 1,
  682. ];
  683. if (!AccountLogModel::insertGetId($data)) {
  684. DB::rollBack();
  685. $this->error = 2033;
  686. return false;
  687. }
  688. }
  689. // 成功
  690. DB::commit();
  691. RedisService::keyDel("caches:balanceLog:total*");
  692. return $this->getInfo($userId, 3, true);
  693. }
  694. } catch (\Exception $exception) {
  695. DB::rollBack();
  696. $this->errorData = ['error' => $exception->getMessage()];
  697. $this->error = 2028;
  698. return false;
  699. }
  700. }
  701. /**
  702. * 更新用户等级
  703. * @param $userId 需要更新等级用户ID
  704. */
  705. public function upgradeUpdate($userId)
  706. {
  707. $cacheKey = "caches:member:levelLock_{$userId}";
  708. if (RedisService::get($cacheKey)) {
  709. $this->error = lang(4303, ['uid' => $userId]);
  710. return false;
  711. }
  712. RedisService::set($cacheKey, date('Y-m-d H:i:s'), rand(5, 10));
  713. $userInfo = $this->model->where(['id' => $userId, 'mark' => 1])
  714. ->select(['id', 'usdt', 'member_level', 'performance','upgrade_status', 'upgrade_at', 'status'])
  715. ->first();
  716. if (empty($userInfo)) {
  717. RedisService::clear($cacheKey);
  718. $this->error = lang(4301, ['uid' => $userId]);
  719. return false;
  720. }
  721. $memberLevel = isset($userInfo['member_level']) ? $userInfo['member_level'] : 0; // 个人等级
  722. $performance = isset($userInfo['performance']) ? $userInfo['performance'] : 0; // 个人业绩
  723. $upgradeStatus = isset($userInfo['upgrade_status']) ? $userInfo['upgrade_status'] : 0; // 升级方式
  724. $teamPerformance = TeamService::make()->getTeamPerformanceByType($userId, 2, true);
  725. $teamPerformance = round($teamPerformance + $performance, 2);
  726. // 等级条件
  727. $nextLevel = MemberLevelModel::where('upgrade_usdt', '<=', $teamPerformance)
  728. ->where(['status' => 1, 'mark' => 1])
  729. ->orderBy('sort', 'desc')
  730. ->orderBy('id', 'desc')
  731. ->value('id');
  732. $nextLevel = $nextLevel>0? intval($nextLevel) : 0;
  733. // 是否只升不降
  734. if ($$upgradeStatus==2 && $nextLevel<=$memberLevel) {
  735. RedisService::clear($cacheKey);
  736. $this->error = lang(4302, ['uid' => $userId]);
  737. return false;
  738. }
  739. // 更新等级
  740. 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()])) {
  741. RedisService::clear($cacheKey);
  742. $this->error = lang(4302, ['uid' => $userId, 'level' => $nextLevel]);
  743. return false;
  744. }
  745. $this->error = lang(4302, ['uid' => $userId, 'level' => $nextLevel, 'old' => $memberLevel]);
  746. RedisService::set($cacheKey, ['level' => $nextLevel, 'old' => $memberLevel, 'date' => date('Y-m-d H:i:s')], rand(30, 60));
  747. return ['msg' => '更新成功', 'uid' => $userId, 'level' => $nextLevel, 'old' => $memberLevel];
  748. }
  749. /**
  750. * 获取可质押用户列表(按批次数量获取)
  751. * @return mixed
  752. */
  753. public function pledgeUserList()
  754. {
  755. try {
  756. $limit = ConfigService::make()->getConfigByCode('pledge_user_count', 500);
  757. $limit = $limit > 0 ? $limit : 500;
  758. $pledgeUsdt = ConfigService::make()->getConfigByCode('pledge_money', 500);
  759. $pledgeUsdt = $pledgeUsdt > 0 ? $pledgeUsdt : 500;
  760. $sbtPrice = PriceLogService::make()->getSbtPrice();
  761. $sbtUsdtFee = ConfigService::make()->getConfigByCode('pledge_sbt_usdt_fee', 0);
  762. $sbtUsdtFee = $sbtUsdtFee > 0 ? floatval($sbtUsdtFee) : 0;
  763. $sbtFee = $sbtUsdtFee && $sbtPrice > 0 ? moneyFormat($sbtUsdtFee / $sbtPrice, 2) : 0;
  764. $datas = $this->model->from('member as a')
  765. ->leftJoin('pledge_orders as b', 'b.user_id', '=', 'a.id')
  766. ->where('a.usdt', '>=', $pledgeUsdt)
  767. ->where('a.sbt', '>=', $sbtFee)
  768. ->where(function($query){
  769. $query->where('b.id', '<=', 0)->orWhere('a.pledge_count', '<=', 0);
  770. })
  771. ->where(['a.pledge_auto' => 1, 'a.status' => 1, 'a.mark' => 1])
  772. ->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'])
  773. ->limit($limit)
  774. ->orderByRaw('rand()')
  775. ->orderBy('a.id', 'asc')
  776. ->get();
  777. return $datas?$datas->toArray() : [];
  778. } catch (\Exception $exception) {
  779. $this->error = $exception->getMessage();
  780. return false;
  781. }
  782. }
  783. /**
  784. * 获取需要更新等级用户列表(更新等级时间超出当前时间则需要更新)
  785. * @return mixed
  786. */
  787. public function getUpgradeUserList()
  788. {
  789. try {
  790. $limit = ConfigService::make()->getConfigByCode('upgrade_user_count', 500);
  791. $limit = $limit > 0 ? $limit : 500;
  792. $datas = $this->model->where('upgrade_at', '>', date('Y-m-d H:i:s'))
  793. ->where(['status' => 1, 'mark' => 1])
  794. ->select(['id', 'pledge_auto', 'usdt', 'sbt', 'profit', 'trade_status', 'parent_ids'])
  795. ->limit($limit)
  796. ->orderByRaw('rand()')
  797. ->orderBy('id', 'asc')
  798. ->get();
  799. return $datas?$datas->toArray() : [];
  800. } catch (\Exception $exception) {
  801. $this->error = $exception->getMessage();
  802. return false;
  803. }
  804. }
  805. }