FinanceService.php 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113
  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\Models\AccountCountModel;
  13. use App\Models\AccountLogModel;
  14. use App\Models\FinanceModel;
  15. use App\Models\MemberModel;
  16. use App\Services\BaseService;
  17. use App\Services\ConfigService;
  18. use App\Services\RedisService;
  19. use Illuminate\Support\Facades\DB;
  20. /**
  21. * 平台账户(财务)-服务类
  22. * @author laravel开发员
  23. * @since 2020/11/12
  24. * Class ActionLogService
  25. * @package App\Services\Common
  26. */
  27. class FinanceService extends BaseService
  28. {
  29. protected static $instance=null;
  30. /**
  31. * 构造函数
  32. * @author laravel开发员
  33. * @since 2020/11/11
  34. * FinanceService constructor.
  35. */
  36. public function __construct()
  37. {
  38. $this->model = new FinanceModel();
  39. }
  40. /**
  41. * 静态入口
  42. * @return static|null
  43. */
  44. public static function make()
  45. {
  46. if (!self::$instance) {
  47. self::$instance = (new static());
  48. }
  49. return self::$instance;
  50. }
  51. /**
  52. * @param $params
  53. * @param int $pageSize
  54. * @return array
  55. */
  56. public function getDataList($params, $pageSize = 15)
  57. {
  58. $where = ['a.mark' => 1];
  59. $status = isset($params['status'])? $params['status'] : 0;
  60. $type = isset($params['type'])? $params['type'] : 0;
  61. if($status>0){
  62. $where['a.status'] = $status;
  63. }
  64. if($type>0){
  65. $where['a.type'] = $type;
  66. }
  67. $list = $this->model->from('finance as a')
  68. ->where($where)
  69. ->where(function ($query) use($params){
  70. // 日期
  71. $date = isset($params['date']) ? $params['date'] : [];
  72. $start = isset($date[0])? $date[0] : '';
  73. $end = isset($date[1])? $date[1] : '';
  74. $end = $start>=$end? '' : $end;
  75. if ($start) {
  76. $query->where('a.create_time','>=', strtotime($start));
  77. }
  78. if($end){
  79. $query->where('a.create_time','<', strtotime($end));
  80. }
  81. })
  82. ->select(['a.*'])
  83. ->orderBy('a.create_time','desc')
  84. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  85. $list = $list? $list->toArray() :[];
  86. if($list){
  87. foreach($list['data'] as &$item){
  88. $item['create_time'] = $item['create_time']? datetime($item['create_time'],'Y-m-d H.i.s') : '';
  89. }
  90. }
  91. return [
  92. 'pageSize'=> $pageSize,
  93. 'total'=>isset($list['total'])? $list['total'] : 0,
  94. 'list'=> isset($list['data'])? $list['data'] : []
  95. ];
  96. }
  97. /**
  98. * 平台结算
  99. * @param $money
  100. * @param int $changeType 交易类型:1-进账,2-出账
  101. * @param int $type 类型:1-消费,2-佣金,3-充值提现转账,4-退款,99-其他
  102. * @param int $coinType 币种类型: 1-USDT,2-星豆
  103. * @return mixed
  104. */
  105. public function saveLog($userId, $money, $changeType = 1, $type=1, $coinType = 1)
  106. {
  107. $date = date('Y-m-d');
  108. $info = $this->model->where(['user_id'=> $userId,'date'=> $date,'type'=> $type,'mark'=>1])->first();
  109. if(!$info){
  110. $data = ['user_id'=>$userId,'date'=> $date,'type'=>$type,'create_time'=>time(),'update_time'=> time(),'status'=>1];
  111. if($changeType==1){
  112. $data['income'] = $money;
  113. }else{
  114. $data['expend'] = $money;
  115. }
  116. return $this->model->insertGetId($data);
  117. }else{
  118. if($changeType == 1){
  119. $info->income += $money;
  120. }else{
  121. $info->expend += $money;
  122. }
  123. return $info->save();
  124. }
  125. }
  126. /**
  127. * 升级收益结算
  128. * @param $userId 升级用户ID
  129. * @param $userInfo 升级用户信息:parents-上级,points-上级节点,parent_id-推荐人,member_level-升级用户等级
  130. * @param $usdt 升级消费的USDT
  131. * @param $orderNo 升级记录单号
  132. * @param string $remark 升级项目备注说明
  133. * @return bool
  134. */
  135. public function settleBonus($userId, $userInfo, $usdt, $orderNo, $remark='')
  136. {
  137. $parents = isset($userInfo['parents'])? $userInfo['parents'] : ''; // 上级
  138. $points = isset($userInfo['points'])? $userInfo['points'] : ''; // 挂靠节点
  139. $parentId = isset($userInfo['parent_id'])? $userInfo['parent_id'] : 0;
  140. $userLevel = isset($userInfo['member_level'])? $userInfo['member_level'] : 0; // 用户等级
  141. RedisService::set("caches:bonus:temp_{$userId}_{$orderNo}", ['info'=> $userInfo,'usdt'=> $usdt,'remark'=> $remark], 6 * 3600);
  142. if($userLevel<=0){
  143. $this->error = 2607;
  144. return false;
  145. }
  146. DB::beginTransaction();
  147. // TODO 直推奖励结算
  148. if($usdt>0 && $parentId>0){
  149. $parentInfo = MemberModel::where(['id'=> $parentId,'mark'=>1])
  150. ->select(['id','usdt','balance','wait_score'])
  151. ->first();
  152. $rate1 = ConfigService::make()->getConfigByCode('award_push_rate',0);
  153. $rate1 = $rate1>0 && $rate1 <100? $rate1 : 0;
  154. $bonusUsdt1 = moneyFormat($usdt * $rate1/100, 4);
  155. if($parentInfo && $bonusUsdt1>0){
  156. // 账户进账
  157. $updateData = [
  158. 'usdt'=> DB::raw("usdt + {$bonusUsdt1}"),
  159. 'upgrade_profit_total'=>DB::raw("upgrade_profit_total + {$bonusUsdt1}"), // 升级累计收益
  160. 'update_time'=>time()
  161. ];
  162. if(!MemberModel::where(['id'=> $parentId,'mark'=>1])->update($updateData)){
  163. DB::rollBack();
  164. $this->error = 2601;
  165. return false;
  166. }
  167. // 收益明细
  168. $log = [
  169. 'user_id' => $parentId,
  170. 'source_id' => $userId,
  171. 'source_order_no' => $orderNo,
  172. 'type' => 12,
  173. 'coin_type' => 1,
  174. 'user_type'=> 1,
  175. 'money' => $bonusUsdt1,
  176. 'actual_money' => $bonusUsdt1,
  177. 'balance' => isset($parentInfo['usdt'])? $parentInfo['usdt'] : 0,
  178. 'create_time' => time(),
  179. 'update_time' => time(),
  180. 'remark' => $remark,
  181. 'status' => 1,
  182. 'mark' => 1,
  183. ];
  184. if(!AccountLogModel::insertGetId($log)){
  185. DB::rollBack();
  186. $this->error = 2602;
  187. return false;
  188. }
  189. // TODO 平台流水(拨出对应比例USDT)
  190. FinanceService::make()->saveLog(0, $bonusUsdt1, 2);
  191. }
  192. }
  193. // TODO 点对点奖励收益结算 (会员升级数必须小于等于节点会员层数,即按同层给奖励)
  194. $points = $points? explode(',', $points) : [];
  195. $points = array_filter($points);
  196. $pointId = isset($points[$userLevel-1])? $points[$userLevel-1] : 0;
  197. if($points && count($points) >= $userLevel && $pointId>0){
  198. // TODO 当前会员升级为N级,且N层上级节点会员等级>=升级会员等级时奖励点对点奖励(否则等级烧伤)
  199. $pointInfo = MemberModel::where(['id'=> $pointId,'mark'=>1])
  200. ->select(['id','usdt','balance','member_level','wait_score'])
  201. ->first();
  202. $pointLevel = isset($pointInfo['member_level'])? $pointInfo['member_level'] : 0;
  203. $rate2 = ConfigService::make()->getConfigByCode('award_node_rate',0);
  204. $rate2 = $rate2>0 && $rate2 <100? $rate2 : 0;
  205. $bonusUsdt2 = moneyFormat($usdt * $rate2/100, 4);
  206. if($pointInfo && $bonusUsdt2>0){
  207. if($pointLevel>= $userLevel){
  208. // 账户进账
  209. $updateData = [
  210. 'usdt'=> DB::raw("usdt + {$bonusUsdt2}"),
  211. 'upgrade_profit_total'=>DB::raw("upgrade_profit_total + {$bonusUsdt2}"), // 升级累计收益
  212. 'update_time'=>time()
  213. ];
  214. if(!MemberModel::where(['id'=> $pointId,'mark'=>1])->update($updateData)){
  215. DB::rollBack();
  216. $this->error = 2603;
  217. return false;
  218. }
  219. // 收益明细
  220. $log = [
  221. 'user_id' => $parentId,
  222. 'source_id' => $userId,
  223. 'source_order_no' => $orderNo,
  224. 'type' => 14,
  225. 'coin_type' => 1,
  226. 'user_type'=> 1,
  227. 'money' => $bonusUsdt2,
  228. 'actual_money' => $bonusUsdt2,
  229. 'balance' => isset($pointInfo['usdt'])? $pointInfo['usdt'] : 0,
  230. 'create_time' => time(),
  231. 'update_time' => time(),
  232. 'remark' => $remark,
  233. 'status' => 1,
  234. 'mark' => 1,
  235. ];
  236. if(!AccountLogModel::insertGetId($log)){
  237. DB::rollBack();
  238. $this->error = 2604;
  239. return false;
  240. }
  241. // TODO 平台流水(拨出对应比例USDT)
  242. FinanceService::make()->saveLog(0, $bonusUsdt2, 2);
  243. }
  244. // 烧伤明细处理(不进账)
  245. else{
  246. $log = [
  247. 'user_id' => $parentId,
  248. 'source_id' => $userId,
  249. 'source_order_no' => $orderNo,
  250. 'type' => 97,
  251. 'coin_type' => 1,
  252. 'user_type'=> 1,
  253. 'money' => $bonusUsdt2,
  254. 'actual_money' => $bonusUsdt2,
  255. 'balance' => isset($pointInfo['usdt'])? $pointInfo['usdt'] : 0,
  256. 'create_time' => time(),
  257. 'update_time' => time(),
  258. 'remark' => $remark,
  259. 'status' => 1,
  260. 'mark' => 1,
  261. ];
  262. if(!AccountLogModel::insertGetId($log)){
  263. DB::rollBack();
  264. $this->error = 2604;
  265. return false;
  266. }
  267. }
  268. }
  269. }
  270. // TODO 管理奖结算(往上找最近的等级为5的倍数且等级大于升级用户的顺位用户,奖励管理奖)
  271. $parents = $parents? explode(',', $parents) : [];
  272. $parents = array_filter($parents);
  273. if($parents){
  274. $awardIndex = -1;
  275. $logs = []; // 明细和烧伤明细
  276. foreach ($parents as $k => $pid){
  277. $parentInfo = MemberModel::where(['id'=> $parentId,'mark'=>1])
  278. ->select(['id','usdt','balance','member_level','wait_score'])
  279. ->first();
  280. $parentLevel = isset($parentInfo['member_level'])? $parentInfo['member_level'] : 0;
  281. $rate3 = ConfigService::make()->getConfigByCode('award_manage_rate',0);
  282. $rate3 = $rate3>0 && $rate3 <100? $rate3 : 0;
  283. $bonusUsdt3 = moneyFormat($usdt * $rate3/100, 4);
  284. if($parentLevel>= $userLevel && ($parentLevel%5==0)){
  285. $awardIndex = $k;
  286. if($bonusUsdt3>0){
  287. // 账户进账
  288. $updateData = [
  289. 'usdt'=> DB::raw("usdt + {$bonusUsdt3}"),
  290. 'upgrade_profit_total'=>DB::raw("upgrade_profit_total + {$bonusUsdt3}"), // 升级累计收益
  291. 'update_time'=>time()
  292. ];
  293. if(!MemberModel::where(['id'=> $pid,'mark'=>1])->update($updateData)){
  294. DB::rollBack();
  295. $this->error = 2605;
  296. return false;
  297. }
  298. // 收益明细
  299. $logs[] = [
  300. 'user_id' => $pid,
  301. 'source_id' => $userId,
  302. 'source_order_no' => $orderNo,
  303. 'type' => 13,
  304. 'coin_type' => 1,
  305. 'user_type'=> 1,
  306. 'money' => $bonusUsdt3,
  307. 'actual_money' => $bonusUsdt3,
  308. 'balance' => isset($parentInfo['usdt'])? $parentInfo['usdt'] : 0,
  309. 'create_time' => time(),
  310. 'update_time' => time(),
  311. 'remark' => $remark,
  312. 'status' => 1,
  313. 'mark' => 1,
  314. ];
  315. }
  316. }
  317. // (已经找到) 剩下的管理奖烧伤
  318. else if($awardIndex>=0){
  319. // 管理烧伤明细
  320. $logs[] = [
  321. 'user_id' => $pid,
  322. 'source_id' => $userId,
  323. 'source_order_no' => $orderNo,
  324. 'type' => 98,
  325. 'coin_type' => 1,
  326. 'user_type'=> 1,
  327. 'money' => $bonusUsdt3,
  328. 'actual_money' => $bonusUsdt3,
  329. 'balance' => isset($parentInfo['usdt'])? $parentInfo['usdt'] : 0,
  330. 'create_time' => time(),
  331. 'update_time' => time(),
  332. 'remark' => $remark,
  333. 'status' => 1,
  334. 'mark' => 1,
  335. ];
  336. }
  337. // 还没找到,即等级条件不满足,等级烧伤
  338. else {
  339. // 等级烧伤明细
  340. $logs[] = [
  341. 'user_id' => $pid,
  342. 'source_id' => $userId,
  343. 'source_order_no' => $orderNo,
  344. 'type' => 97,
  345. 'coin_type' => 1,
  346. 'user_type'=> 1,
  347. 'money' => $bonusUsdt3,
  348. 'actual_money' => $bonusUsdt3,
  349. 'balance' => isset($parentInfo['usdt'])? $parentInfo['usdt'] : 0,
  350. 'create_time' => time(),
  351. 'update_time' => time(),
  352. 'remark' => $remark,
  353. 'status' => 1,
  354. 'mark' => 1,
  355. ];
  356. }
  357. }
  358. if($logs && !AccountLogModel::insert($logs)){
  359. DB::rollBack();
  360. $this->error = 2606;
  361. return false;
  362. }
  363. }
  364. DB::commit();
  365. $this->error = 2608;
  366. return true;
  367. }
  368. /**
  369. * 任务算力奖励
  370. * @param $userId 用户ID
  371. * @param $power 算力
  372. * @param $type 类型
  373. * @param int $sourceId 任务ID
  374. * @param string $remark 备注说明
  375. * @return false
  376. */
  377. public function settleTaskPower($userId, $power, $type, $sourceId=0, $remark='')
  378. {
  379. if($power<=0){
  380. $this->error = 2014;
  381. return false;
  382. }
  383. $userInfo = MemberModel::where(['id'=> $userId, 'status'=>1,'mark'=>1])
  384. ->select(['id','nickname','usdt','power_num','status'])
  385. ->first();
  386. $userPower = isset($userInfo['power_num'])? $userInfo['power_num'] : 0;
  387. if(empty($userInfo) || $userId<=0)
  388. {
  389. $this->error = 1041;
  390. return false;
  391. }
  392. DB::beginTransaction();
  393. // 更新账户算力
  394. $updateData = ['power_num'=> DB::raw("power_num + {$power}"),'update_time'=>time()];
  395. if(!MemberModel::where(['id'=> $userId])->update($updateData)){
  396. DB::rollBack();
  397. $this->error = 1042;
  398. return false;
  399. }
  400. // 明细
  401. $orderNo = get_order_num('TS');
  402. $log = [
  403. 'user_id' => $userId,
  404. 'source_id' => $sourceId,
  405. 'source_order_no' => $orderNo,
  406. 'type' => $type?$type:99,
  407. 'coin_type' => 3,
  408. 'user_type'=> 1,
  409. 'money' => $power,
  410. 'actual_money' => $power,
  411. 'balance' => $userPower,
  412. 'create_time' => time(),
  413. 'update_time' => time(),
  414. 'remark' => $remark? $remark : '算力奖励',
  415. 'status' => 1,
  416. 'mark' => 1,
  417. ];
  418. if (!AccountLogModel::insertGetId($log)) {
  419. $this->error = 2407;
  420. DB::rollBack();
  421. return false;
  422. }
  423. DB::commit();
  424. // 算力统计
  425. AccountLogService::make()->saveCount($userId, $power, 1);
  426. // 站内消息
  427. $dateTime = date('Y-m-d H:i:s');
  428. MessageService::make()->pushMessage($userId, $log['remark'] , "您在{$dateTime}(UTC+8){$log['remark']}{$power}算力已到账,请及时查看账户!!!",3);
  429. }
  430. /**
  431. * 订单结算
  432. * @param $orderInfo 订单信息
  433. * @param $orderXdTotal 星豆数量
  434. * @param int $userId
  435. * @return bool
  436. */
  437. public function settleOrder($orderInfo, $orderXdTotal, $userId=0)
  438. {
  439. //$orderXdTotal = isset($orderInfo['xd_total'])?$orderInfo['xd_total'] : 0;
  440. $orderId = isset($orderInfo['id'])?$orderInfo['id'] : 0;
  441. $orderNo = isset($orderInfo['order_no'])?$orderInfo['order_no'] : '';
  442. $orderUserId = isset($orderInfo['user_id'])?$orderInfo['user_id'] : 0;
  443. $orderMerchUid = isset($orderInfo['merch_uid'])?$orderInfo['merch_uid'] : 0;
  444. if(empty($orderId) || empty($orderUserId)){
  445. $this->error = 2912;
  446. return true;
  447. }
  448. if($orderXdTotal <= 0){
  449. $this->error = 3005;
  450. return true;
  451. }
  452. $cacheKey = "caches:settle:{$orderUserId}_{$orderNo}";
  453. if(RedisService::get($cacheKey)){
  454. $this->error = 3002;
  455. return true;
  456. }
  457. // 奖励待返积分、算力
  458. $awardWaitScore = isset($orderInfo['award_wait_score'])?$orderInfo['award_wait_score'] : 0;
  459. $awardPowerNum = isset($orderInfo['award_power_num'])?$orderInfo['award_power_num'] : 0;
  460. // 订单用户信息
  461. $userInfo = MemberModel::with(['parent'])
  462. ->where(['id'=> $orderUserId,'mark'=> 1,'status'=> 1])
  463. ->select(['id','nickname','pay_password','balance','usdt','power_num','wait_score','parent_id','parents'])
  464. ->first();
  465. $userInfo = $userInfo? $userInfo->toArray() : [];
  466. $parentInfo = isset($userInfo['parent'])? $userInfo['parent'] : [];
  467. $parentId = isset($userInfo['parent_id'])? $userInfo['parent_id'] : 0;
  468. $userXd = isset($userInfo['balance'])? floatval($userInfo['balance']) : 0.00;
  469. $userWaitScore = isset($userInfo['wait_score'])? floatval($userInfo['wait_score']) : 0.00;
  470. $userPowerNum = isset($userInfo['power_num'])? floatval($userInfo['power_num']) : 0.00;
  471. if(empty($userInfo)){
  472. $this->error = 3003;
  473. RedisService::clear($cacheKey);
  474. return true;
  475. }
  476. // 推荐用户奖励(从用户奖励中扣除)
  477. $inviteAwardWaitScore = 0;
  478. $userAwardWaitScore = $awardWaitScore;
  479. $parentStatus = isset($parentInfo['status'])? $parentInfo['status'] : 0;
  480. if($parentInfo && $parentStatus==1 && $awardWaitScore>0){
  481. // 奖励上级待返积分
  482. $inviteWaitScoreRate = ConfigService::make()->getConfigByCode('cost_award_invite_wait_score',0);
  483. $inviteWaitScoreRate = $inviteWaitScoreRate>0 && $inviteWaitScoreRate<100? $inviteWaitScoreRate : 0;
  484. $inviteAwardWaitScore = moneyFormat($awardWaitScore * $inviteWaitScoreRate/100, 2);
  485. $userAwardWaitScore = moneyFormat($awardWaitScore - $inviteAwardWaitScore, 2);
  486. }
  487. // 没有佣金
  488. if($userAwardWaitScore<=0 && $userPowerNum<=0){
  489. $this->error = 3004;
  490. RedisService::clear($cacheKey);
  491. return true;
  492. }
  493. // TODO 结算处理
  494. DB::beginTransaction();
  495. // TODO 订单商户佣金结算
  496. if ($orderMerchUid > 0){
  497. $merchantUserInfo = MemberModel::where(['id'=> $orderMerchUid,'mark'=>1])
  498. ->select(['id','balance','wait_score','usdt','status'])
  499. ->first();
  500. // 商户佣金计算入账
  501. $settleRate = ConfigService::make()->getConfigByCode('merchant_settle_usdt_rate');
  502. $settleRate = $settleRate>0? min(100, $settleRate) : 100;
  503. $settleXd = moneyFormat($orderXdTotal * $settleRate/100, 2);
  504. $xdPrice = ConfigService::make()->getConfigByCode('xd_price',100);
  505. $xdPrice = $xdPrice>0 && $xdPrice<10000? $xdPrice : 100;
  506. $settleUsdt = moneyFormat($settleXd/$xdPrice, 2);
  507. if($settleUsdt>0 && $merchantUserInfo){
  508. $updateData = ['usdt'=> DB::raw("usdt + {$settleUsdt}"),'update_time'=>time()];
  509. if(!MemberModel::where(['id'=> $orderMerchUid])->update($updateData)){
  510. DB::rollBack();
  511. $this->error = 1042;
  512. return false;
  513. }
  514. // 明细
  515. $merchantUsdt = isset($merchantUserInfo['usdt'])? $merchantUserInfo['usdt'] : 0;
  516. $log = [
  517. 'user_id' => $orderMerchUid,
  518. 'source_id' => $orderUserId,
  519. 'source_order_no' => $orderNo,
  520. 'type' => 10,
  521. 'coin_type' => 1,
  522. 'user_type'=> 1,
  523. 'money' => $settleUsdt,
  524. 'actual_money' => $settleUsdt,
  525. 'balance' => $merchantUsdt,
  526. 'create_time' => time(),
  527. 'update_time' => time(),
  528. 'remark' => "推荐商品佣金奖励",
  529. 'status' => 1,
  530. 'mark' => 1,
  531. ];
  532. if(!AccountLogModel::insertGetId($log)){
  533. DB::rollBack();
  534. $this->error = 2029;
  535. RedisService::clear($cacheKey);
  536. return false;
  537. }
  538. }
  539. }
  540. if($userAwardWaitScore>0 || $awardPowerNum>0){
  541. // TODO 购买用户奖励结算
  542. $updateData = [
  543. 'wait_score'=>DB::raw("wait_score + {$userAwardWaitScore}"), // 用户待返积分奖励
  544. 'power_num'=>DB::raw("power_num + {$awardPowerNum}"), // 算力奖励
  545. 'update_time'=>time()
  546. ];
  547. if(!MemberModel::where(['id'=> $orderUserId])->update($updateData)){
  548. DB::rollBack();
  549. $this->error = 1042;
  550. RedisService::clear($cacheKey);
  551. return false;
  552. }
  553. }
  554. // 待返积分奖励明细
  555. if($userAwardWaitScore>0){
  556. $log = [
  557. 'user_id' => $orderUserId,
  558. 'source_id' => $orderId,
  559. 'source_order_no' => $orderNo,
  560. 'type' => 9,
  561. 'coin_type' => 5,
  562. 'user_type'=> 1,
  563. 'money' => $userAwardWaitScore,
  564. 'actual_money' => $userAwardWaitScore,
  565. 'balance' => $userWaitScore,
  566. 'create_time' => time(),
  567. 'update_time' => time(),
  568. 'remark' => "商城消费奖励",
  569. 'status' => 1,
  570. 'mark' => 1,
  571. ];
  572. if(!AccountLogModel::insertGetId($log)){
  573. DB::rollBack();
  574. $this->error = 2029;
  575. RedisService::clear($cacheKey);
  576. return false;
  577. }
  578. // 用户消息
  579. $dateTime = date('Y-m-d H:i:s');
  580. $message = "您在{$dateTime}(UTC+8)完成商城消费,获得待返积分奖励已到账:\n消费星豆:{$orderXdTotal}\n奖励积分:{$userAwardWaitScore}\n奖励前:{$userWaitScore}";
  581. MessageService::make()->pushMessage($orderUserId, '商城消费待返积分奖励', $message,3);
  582. }
  583. // 算力奖励明细
  584. if($awardPowerNum>0){
  585. $log = [
  586. 'user_id' => $orderUserId,
  587. 'source_id' => $orderId,
  588. 'source_order_no' => $orderNo,
  589. 'type' => 9,
  590. 'coin_type' => 3,
  591. 'user_type'=> 1,
  592. 'money' => $awardPowerNum,
  593. 'actual_money' => $awardPowerNum,
  594. 'balance' => $userPowerNum,
  595. 'create_time' => time(),
  596. 'update_time' => time(),
  597. 'remark' => "商城消费奖励",
  598. 'status' => 1,
  599. 'mark' => 1,
  600. ];
  601. if(!AccountLogModel::insertGetId($log)){
  602. DB::rollBack();
  603. $this->error = 2029;
  604. RedisService::clear($cacheKey);
  605. return false;
  606. }
  607. // 用户消息
  608. $dateTime = date('Y-m-d H:i:s');
  609. $message = "您在{$dateTime}(UTC+8)完成商城消费,获得算力奖励已到账:\n消费星豆:{$orderXdTotal}\n奖励算力:{$awardPowerNum}\n奖励前:{$userPowerNum}";
  610. MessageService::make()->pushMessage($orderUserId, '商城消费算力奖励', $message,3);
  611. // 算力统计
  612. AccountLogService::make()->saveCount($orderUserId, $userPowerNum, 1);
  613. }
  614. // TODO 推荐用户待返积分奖励明细
  615. if($inviteAwardWaitScore>0 && $parentId>0 && $parentId != $orderUserId){
  616. $updateData = [
  617. 'wait_score'=>DB::raw("wait_score + {$inviteAwardWaitScore}"), // 推荐用户待返积分奖励
  618. 'update_time'=>time()
  619. ];
  620. if(!MemberModel::where(['id'=> $parentId])->update($updateData)){
  621. DB::rollBack();
  622. $this->error = 2028;
  623. RedisService::clear($cacheKey);
  624. return false;
  625. }
  626. // 明细
  627. $parentWaitScore = isset($parentInfo['wait_score'])? $parentInfo['wait_score'] : 0;
  628. $log = [
  629. 'user_id' => $parentId,
  630. 'source_id' => $orderUserId,
  631. 'source_order_no' => $orderNo,
  632. 'type' => 9,
  633. 'coin_type' => 5,
  634. 'user_type'=> 1,
  635. 'money' => $inviteAwardWaitScore,
  636. 'actual_money' => $inviteAwardWaitScore,
  637. 'balance' => $parentWaitScore,
  638. 'create_time' => time(),
  639. 'update_time' => time(),
  640. 'remark' => "推荐用户商城消费奖励",
  641. 'status' => 1,
  642. 'mark' => 1,
  643. ];
  644. if(!AccountLogModel::insertGetId($log)){
  645. DB::rollBack();
  646. $this->error = 2029;
  647. RedisService::clear($cacheKey);
  648. return false;
  649. }
  650. // 用户消息
  651. $dateTime = date('Y-m-d H:i:s');
  652. $message = "您在{$dateTime}(UTC+8)获得推荐用户【{$orderUserId}】商城消费,待返积分奖励已到账:\n消费星豆:{$orderXdTotal}\n奖励积分:{$inviteAwardWaitScore}\n奖励前:{$parentWaitScore}";
  653. MessageService::make()->pushMessage($orderUserId, '推荐用户商城消费奖励', $message,3);
  654. }
  655. DB::commit();
  656. RedisService::clear($cacheKey);
  657. return ['user_award_score'=>$userAwardWaitScore,'user_award_power'=> $userPowerNum,'invite_score'=>$inviteAwardWaitScore];
  658. }
  659. /**
  660. * 每日平台发放积分
  661. * @return bool
  662. */
  663. public function grantScore()
  664. {
  665. $cacheKey = "caches:platform:grant_score";
  666. if(RedisService::get($cacheKey.'_lock')){
  667. $this->error = 3006;
  668. return false;
  669. }
  670. $dayScore = ConfigService::make()->getConfigByCode('xb_day_num',0); // 每日发放
  671. $dayScore = $dayScore>0 && $dayScore<=10000000? $dayScore : 0;
  672. $xlTotal = ConfigService::make()->getConfigByCode('xl_total',0); // 总发放
  673. $xlTotal = $xlTotal? $xlTotal : 0;
  674. if($xlTotal<=0 || $dayScore <= 0 || $dayScore > $xlTotal){
  675. $this->error = 3007;
  676. return false;
  677. }
  678. // 发放用户
  679. RedisService::set($cacheKey.'_lock', date('Y-m-d H:i:s'), rand(30,60));
  680. $date = date('Y-m-d',strtotime('-1 day'));
  681. $model = AccountCountModel::from('account_counts as a')
  682. ->leftJoin('member as b','b.id','=','a.user_id')
  683. ->leftJoin('member_level as c','c.id','=','b.member_level')
  684. ->where(['a.date'=>$date,'a.type'=>1]);
  685. $countModel = clone $model;
  686. $powerDayTotal = $countModel->sum('a.money');
  687. $settleUsers = $model->where('b.score_grant_at','<',date('Y-m-d'))
  688. ->select(['a.user_id','a.type','a.money','b.member_level','b.supper_point','b.score','c.power_multiple'])
  689. ->orderBy('a.create_time','asc')
  690. ->groupBy('a.user_id')
  691. ->limit(rand(200,500))
  692. ->get();
  693. $settleUsers = $settleUsers? $settleUsers->toArray() : [];
  694. if($settleUsers){
  695. RedisService::set($cacheKey.'_'.date('YmdHis'), ['power'=> $powerDayTotal,'users'=>$settleUsers], 7200);
  696. foreach($settleUsers as $item){
  697. $dayPower = isset($item['money'])? $item['money'] : 0;
  698. $userId = isset($item['user_id'])? $item['user_id'] : 0;
  699. $powerRate = isset($item['power_multiple']) && $item['power_multiple']? $item['power_multiple'] : 1;
  700. $userSettleScore = moneyFormat(($dayPower * $powerRate)/$powerDayTotal * $dayScore, 2);
  701. if($userSettleScore>0 && $userId>0){
  702. // 节点分红积分奖励
  703. $nodeScore = 0;
  704. $nodeName = '节点会员';
  705. $nodeId = isset($item['supper_point'])? $item['supper_point'] : 0;
  706. if($nodeId>0){
  707. $nodeInfo = MemberNodeService::make()->getNodeInfo($nodeId);
  708. $scoreRate = isset($nodeInfo['score_rate'])? $nodeInfo['score_rate'] : 0;
  709. if($scoreRate>0 && $scoreRate<100){
  710. $nodeName = isset($nodeInfo['name']) && $nodeInfo['name']? $nodeInfo['name'] : '节点会员';
  711. $nodeScore = moneyFormat($userSettleScore * $scoreRate/100, 2);
  712. }
  713. }
  714. // 结算发放积分
  715. $totalScore = moneyFormat($userSettleScore + $nodeScore,2);
  716. DB::beginTransaction();
  717. $updateData = [
  718. 'score'=> DB::raw("score + {$totalScore}"),
  719. 'score_grant_at'=> date('Y-m-d H:i:s'),
  720. 'update_time'=> time(),
  721. ];
  722. if(!MemberModel::where(['id'=> $userId])->update($updateData)){
  723. DB::rollBack();
  724. $this->error = 3007;
  725. continue;
  726. }
  727. // 明细
  728. $userScore = isset($item['score'])? $item['score'] : 0;
  729. $log = [
  730. 'user_id' => $userId,
  731. 'source_id' => 0,
  732. 'source_order_no' => get_order_num('SC'),
  733. 'type' => 9,
  734. 'coin_type' => 4,
  735. 'user_type'=> 1,
  736. 'money' => $userSettleScore,
  737. 'actual_money' => $userSettleScore,
  738. 'balance' => $userScore,
  739. 'create_time' => time(),
  740. 'update_time' => time(),
  741. 'remark' => "每日发放积分",
  742. 'status' => 1,
  743. 'mark' => 1,
  744. ];
  745. if(!AccountLogModel::insertGetId($log)){
  746. DB::rollBack();
  747. $this->error = 2029;
  748. continue;
  749. }
  750. if($nodeScore>0){
  751. $userScore += $userSettleScore;
  752. $log = [
  753. 'user_id' => $userId,
  754. 'source_id' => 0,
  755. 'source_order_no' => get_order_num('SC'),
  756. 'type' => 9,
  757. 'coin_type' => 4,
  758. 'user_type'=> 1,
  759. 'money' => $nodeScore,
  760. 'actual_money' => $nodeScore,
  761. 'balance' => moneyFormat($userScore + $userSettleScore,4),
  762. 'create_time' => time(),
  763. 'update_time' => time(),
  764. 'remark' => "{$nodeName}会员每日积分分红",
  765. 'status' => 1,
  766. 'mark' => 1,
  767. ];
  768. if(!AccountLogModel::insertGetId($log)){
  769. DB::rollBack();
  770. $this->error = 2029;
  771. continue;
  772. }
  773. }
  774. DB::commit();
  775. // 用户消息
  776. $dateTime = date('Y-m-d H:i:s');
  777. $message = "您在{$dateTime}(UTC+8)获得平台每日积分发放已到账:\n发放积分:{$dayScore}\n到账积分:{$userSettleScore}\n发放前:{$userScore}\n节点会员:{$nodeName}\n节点分红:{$nodeScore}";
  778. MessageService::make()->pushMessage($userId, '每日积分发放', $message,3);
  779. }
  780. }
  781. RedisService::clear($cacheKey.'_lock');
  782. }else{
  783. // 结算完
  784. RedisService::set($cacheKey.'_lock', date('Y-m-d H:i:s'), 86400);
  785. }
  786. return ['count'=> count($settleUsers),'power'=>$powerDayTotal,'day_score'=>$dayScore,'xl_total'=> $xlTotal];
  787. }
  788. /**
  789. * 每日返还待返积分
  790. * @return bool
  791. */
  792. public function returnWaitScore()
  793. {
  794. $cacheKey = "caches:platform:wait_score";
  795. if(RedisService::get($cacheKey.'_lock')){
  796. $this->error = 3006;
  797. return false;
  798. }
  799. // 每日日返还待返积分数量
  800. $waitScoreRate = ConfigService::make()->getConfigByCode('day_wait_score_rate',0);
  801. $waitScoreRate = $waitScoreRate>0 && $waitScoreRate<100? $waitScoreRate : 0;
  802. if($waitScoreRate <= 0){
  803. $this->error = 3009;
  804. return false;
  805. }
  806. RedisService::set($cacheKey.'_lock', date('Y-m-d H:i:s'),rand(30,60));
  807. $users = MemberModel::where(['mark'=>1])
  808. ->where('wait_score','>',0)
  809. ->where('wait_score_return_at','<',date('Y-m-d'))
  810. ->select(['id','usdt','score','balance','wait_score'])
  811. ->orderBy('create_time','asc')
  812. ->limit(rand(200,500))
  813. ->get();
  814. $users = $users? $users->toArray() : [];
  815. if($users){
  816. $dateTime = date('Y-m-d H:i:s');
  817. RedisService::set($cacheKey, ['return_rate'=>$waitScoreRate,'users'=>$users,'date'=>$dateTime], 86400);
  818. foreach($users as $item){
  819. $userXd = isset($item['balance'])? $item['balance'] : 0;
  820. $waitScore = isset($item['wait_score'])? $item['wait_score'] : 0;
  821. $userId = isset($item['id'])? $item['id'] : 0;
  822. $settleXd = moneyFormat($waitScore * $waitScoreRate/100, 2); //
  823. if($settleXd>0){
  824. DB::beginTransaction();
  825. $updateData = [
  826. 'wait_score'=> DB::raw("wait_score - {$settleXd}"), // 扣除待返积分
  827. 'balance'=> DB::raw("balance + {$settleXd}"), // 返还星豆数量
  828. 'wait_score_return_at'=> date('Y-m-d H:i:s'),
  829. 'update_time'=> time(),
  830. ];
  831. if(!MemberModel::where(['id'=> $userId])->update($updateData)){
  832. DB::rollBack();
  833. $this->error = 3007;
  834. continue;
  835. }
  836. // 待返积分明细
  837. $orderNo = get_order_num('FS');
  838. if($settleXd){
  839. $log = [
  840. 'user_id' => $userId,
  841. 'source_id' => 0,
  842. 'source_order_no' => $orderNo,
  843. 'type' => 24,
  844. 'coin_type' => 5,
  845. 'user_type'=> 1,
  846. 'money' => -$settleXd,
  847. 'actual_money' => -$settleXd,
  848. 'balance' => $waitScore,
  849. 'create_time' => time(),
  850. 'update_time' => time(),
  851. 'remark' => "每日待返积分返还星豆",
  852. 'status' => 1,
  853. 'mark' => 1,
  854. ];
  855. if(!AccountLogModel::insertGetId($log)){
  856. DB::rollBack();
  857. $this->error = 2029;
  858. continue;
  859. }
  860. }
  861. // 星豆明细
  862. if($settleXd){
  863. $log = [
  864. 'user_id' => $userId,
  865. 'source_id' => 0,
  866. 'source_order_no' => $orderNo,
  867. 'type' => 24,
  868. 'coin_type' => 2,
  869. 'user_type'=> 1,
  870. 'money' => $settleXd,
  871. 'actual_money' => $settleXd,
  872. 'balance' => $userXd,
  873. 'create_time' => time(),
  874. 'update_time' => time(),
  875. 'remark' => "每日待返积分返还星豆",
  876. 'status' => 1,
  877. 'mark' => 1,
  878. ];
  879. if(!AccountLogModel::insertGetId($log)){
  880. DB::rollBack();
  881. $this->error = 2029;
  882. continue;
  883. }
  884. }
  885. DB::commit();
  886. // 用户消息
  887. $dateTime = date('Y-m-d H:i:s');
  888. $message = "您在{$dateTime}(UTC+8)获得每日积分返还已到账:\n返还积分:{$settleXd}\n返还前:{$waitScore}\n返还星豆:{$settleXd} \n返还前:{$userXd} 星豆\n";
  889. MessageService::make()->pushMessage($userId, '每日积分返还星豆奖励', $message,3);
  890. }
  891. }
  892. RedisService::clear($cacheKey.'_lock');
  893. }else{
  894. RedisService::set($cacheKey.'_lock', date('Y-m-d H:i:s'), 86400);
  895. }
  896. return ['count'=> count($users),'return'=> $settleXd];
  897. }
  898. /**
  899. * 全球分红
  900. * @return bool
  901. */
  902. public function globalBonus()
  903. {
  904. $cacheKey = "caches:platform:global_bonus";
  905. if(RedisService::get($cacheKey.'_lock')){
  906. $this->error = 3006;
  907. return false;
  908. }
  909. // 昨日业绩
  910. $date = date('Y-m-d', strtotime('-1 day'));
  911. $model = AccountCountModel::from('account_counts as a')
  912. ->leftJoin('member as b','b.id','=','a.user_id')
  913. ->where(['a.date'=>$date,'a.type'=>2]);
  914. $countModel1 = clone $model; // 普通节点
  915. $countModel2 = clone $model; // 超级节点
  916. $node1Total = $countModel1->where(['b.supper_point'=>1])->sum('a.money');
  917. $node2Total = $countModel2->where(['b.supper_point'=>2])->sum('a.money');
  918. // 无任何节点业绩
  919. if($node1Total <= 0 && $node2Total <= 0){
  920. $this->error = 3010;
  921. return false;
  922. }
  923. // 结算用户
  924. $users = MemberModel::from('member as a')
  925. ->leftJoin('member_nodes as b','b.id','=','a.supper_point')
  926. ->leftJoin('member_level as c','c.id','=','a.member_level')
  927. ->where('a.supper_point','>',0)
  928. ->where('a.global_bonus_at','<',date('Y-m-d'))
  929. ->where(['a.mark'=>1])
  930. ->select(['a.id','a.balance','a.usdt','a.supper_point','a.parent_id','a.member_level','c.global_bonus_rate','b.name'])
  931. ->orderBy('a.supper_point','asc')
  932. ->orderBy('a.id','asc')
  933. ->limit(rand(200,500))
  934. ->get();
  935. $users = $users? $users->toArray() : [];
  936. $success = 0;
  937. if($users) {
  938. $dateTime = date('Y-m-d H:i:s');
  939. RedisService::set($cacheKey, ['node1Total'=>$node1Total,'node2Total'=>$node2Total,'users'=>$users,'date'=>$dateTime], 86400);
  940. foreach ($users as $item){
  941. $userUsdt = isset($item['usdt'])? $item['usdt'] : 0;
  942. $userId = isset($item['id'])? $item['id'] : 0;
  943. $userSupperPoint = isset($item['supper_point'])? $item['supper_point'] : 0;
  944. $bonusRate = isset($item['global_bonus_rate'])? $item['global_bonus_rate'] : 0;
  945. if($bonusRate<=0 || $bonusRate>=100 || $userSupperPoint<=0){
  946. continue;
  947. }
  948. // 个人昨日业绩
  949. $userPerformance = AccountLogService::make()->getTotal($userId, $date,2);
  950. // 团队昨日业绩
  951. $teamPerformance = AccountLogService::make()->getTeamTotal($userId, $date,2);
  952. // 普通节点
  953. $nodeTotal = 0;
  954. if($userSupperPoint==1){
  955. $nodeTotal = $node1Total;
  956. }
  957. // 超级节点
  958. else if($userSupperPoint == 2){
  959. $nodeTotal = $node2Total;
  960. }
  961. $bonusUsdt = moneyFormat(($teamPerformance/$nodeTotal) * $bonusRate/100,4);
  962. if($bonusUsdt>0){
  963. DB::beginTransaction();
  964. $updateData = [
  965. 'usdt'=> DB::raw("usdt + {$bonusUsdt}"), // 奖励USDT
  966. 'global_bonus_at'=> date('Y-m-d H:i:s'),
  967. 'update_time'=> time(),
  968. ];
  969. if(!MemberModel::where(['id'=> $userId])->update($updateData)){
  970. DB::rollBack();
  971. $this->error = 3007;
  972. continue;
  973. }
  974. // 待返积分明细
  975. $orderNo = get_order_num('GU');
  976. $log = [
  977. 'user_id' => $userId,
  978. 'source_id' => 0,
  979. 'source_order_no' => $orderNo,
  980. 'type' => 15,
  981. 'coin_type' => 5,
  982. 'user_type'=> 1,
  983. 'money' => $bonusUsdt,
  984. 'actual_money' => $bonusUsdt,
  985. 'balance' => $userUsdt,
  986. 'create_time' => time(),
  987. 'update_time' => time(),
  988. 'remark' => "全球分红奖励",
  989. 'status' => 1,
  990. 'mark' => 1,
  991. ];
  992. if(!AccountLogModel::insertGetId($log)){
  993. DB::rollBack();
  994. $this->error = 2029;
  995. continue;
  996. }
  997. // 平台财务
  998. FinanceService::make()->saveLog(0,$bonusUsdt,2);
  999. // 用户消息
  1000. $dateTime = date('Y-m-d H:i:s');
  1001. $nodeName = isset($item['name'])? $item['name'] :'';
  1002. $message = "您在{$dateTime}(UTC+8)获得全球分红奖励已到账:\n奖励金额:{$bonusUsdt}\n奖励前:{$userUsdt}\n节点类型:{$nodeName}\n个人算力:{$userPerformance}\n团队算力:{$teamPerformance}\n节点算力:{$nodeTotal}";
  1003. MessageService::make()->pushMessage($userId, '全球分红奖励', $message,3);
  1004. }
  1005. }
  1006. RedisService::clear($cacheKey.'_lock');
  1007. }else{
  1008. RedisService::set($cacheKey.'_lock', date('Y-m-d H:i:s'), 86400);
  1009. }
  1010. return ['count'=>count($users),'success'=> $success];
  1011. }
  1012. }