OrderServices.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. <?php
  2. namespace App\Services;
  3. use App\dao\Estatisticas\RechargeWithDraw;
  4. use App\Facade\TableName;
  5. use App\Game\GlobalUserInfo;
  6. use App\Game\Services\AgentService;
  7. use App\Http\Controllers\Api\AgentController;
  8. use App\Http\helper\Helper;
  9. use App\Http\helper\HttpCurl;
  10. use App\Http\helper\NumConfig;
  11. use App\Jobs\AfEvent;
  12. use App\Models\AgentUser;
  13. use App\Models\RecordScoreInfo;
  14. use App\Models\RecordUserDataStatistics;
  15. use App\Util;
  16. use Illuminate\Support\Facades\DB;
  17. use Illuminate\Support\Facades\Log;
  18. use Illuminate\Support\Facades\Redis;
  19. class OrderServices
  20. {
  21. public $FirstCharge = 30;
  22. public $FirstChargeGive = 20;
  23. public $FirstGiftID = 301;
  24. private $first_pay = null;
  25. public function __construct()
  26. {
  27. }
  28. /**
  29. * 获取支付金额
  30. * @param int $GiftsID 礼包ID
  31. * @param int $user_id 用户ID
  32. * @param int $payAmt 支付金额(元)
  33. * @return array|void [$give, $favorable_price, $Recharge, $czReason, $cjReason] 赠送金额,赠送金额+充值金额,充值金额,充值原因,彩金原因
  34. */
  35. public function getPayInfo($GiftsID, $user_id, $payAmt)
  36. {
  37. $give = $czReason = $cjReason = $Recharge = $favorable_price = $second_give = 0;
  38. $shouldCreateGiftRecord = false; // 是否需要创建首充礼包记录
  39. // 判断是不是首冲礼包
  40. if (!empty($GiftsID)) {
  41. if ($GiftsID == 301) { // 礼包--首冲
  42. // 检查用户是否已购买过首充礼包
  43. $hasPurchased = DB::connection('write')->table('agent.dbo.first_pay_gift_records')
  44. ->where('user_id', $user_id)
  45. ->exists();
  46. if ($hasPurchased) {
  47. // 已购买首充礼包,走普通充值逻辑(只加本金)
  48. $Recharge = $payAmt;
  49. $give = 0;
  50. $favorable_price = $Recharge + $give;
  51. $czReason = 1;
  52. $cjReason = 45;
  53. } else {
  54. // 首次购买首充礼包,走赠送逻辑(立即获得bonus_instantly%)
  55. $Gifts = DB::connection('write')->table('agent.dbo.recharge_gift')->where('gift_id', $GiftsID)->first();
  56. $favorable_price = round($Gifts->bonus_instantly*$payAmt/100,2);
  57. $give = $favorable_price-$payAmt;
  58. $Recharge = $payAmt;
  59. $czReason = 50;
  60. $cjReason = 51;
  61. // 创建首充礼包记录
  62. try {
  63. $this->createFirstPayGiftRecord($user_id, $GiftsID, $payAmt);
  64. } catch (\Exception $e) {
  65. \Log::error('首充礼包记录创建失败', [
  66. 'user_id' => $user_id,
  67. 'gift_id' => $GiftsID,
  68. 'error' => $e->getMessage()
  69. ]);
  70. }
  71. }
  72. }else if ($GiftsID > 400) {
  73. $Status = 1;
  74. $recharge_gear = DB::connection('write')->table('agent.dbo.recharge_gear')->where('status', $Status)->where('money', $payAmt)->select('favorable_price', 'give')->first();
  75. if(!$recharge_gear){
  76. $Recharge=$payAmt;
  77. $give=0;
  78. }else{
  79. $Recharge = $recharge_gear->favorable_price;
  80. $give = $recharge_gear->give;
  81. }
  82. $favorable_price = $Recharge + $give;
  83. $czReason = 1;
  84. $cjReason = 45;
  85. }
  86. } else { // 普通订单
  87. $Status = 1;
  88. $recharge_gear = DB::connection('write')->table('agent.dbo.recharge_gear')->where('status', $Status)->where('money', $payAmt)->select('favorable_price', 'give')->first();
  89. if(!$recharge_gear){
  90. $Recharge=$payAmt;
  91. $give=0;
  92. }else{
  93. $Recharge = $recharge_gear->favorable_price;
  94. $give = $recharge_gear->give;
  95. }
  96. $favorable_price = $Recharge + $give;
  97. $czReason = 1;
  98. $cjReason = 45;
  99. }
  100. return [$give, $favorable_price, $Recharge, $czReason, $cjReason, $second_give];
  101. }
  102. /**
  103. * 添加玩家充值记录
  104. * @param $user_id
  105. * @param $payAmt
  106. * @param $favorable_price
  107. * @param $order_sn
  108. * @param $GiftsID
  109. * @param $Recharge
  110. * @param $czReason
  111. * @param $give
  112. * @param $cjReason
  113. * @param $AdId
  114. * @param $eventType
  115. */
  116. public function addRecord($user_id, $payAmt, $favorable_price, $order_sn, $GiftsID, $Recharge, $czReason, $give, $cjReason, $AdId, $eventType)
  117. {
  118. if ($payAmt > 0) {
  119. // 增加玩家充值金额
  120. $query = DB::connection('write')->table('QPAccountsDB.dbo.YN_VIPAccount')
  121. ->where('UserID', $user_id)
  122. ->value('Recharge');
  123. if ($query) {
  124. DB::connection('write')->table('QPAccountsDB.dbo.YN_VIPAccount')
  125. ->where('UserID', $user_id)
  126. ->increment('Recharge', $payAmt);
  127. } else {
  128. DB::connection('write')->table('QPAccountsDB.dbo.YN_VIPAccount')
  129. ->where('UserID', $user_id)
  130. ->insert(['Recharge' => $payAmt, 'UserID' => $user_id]);
  131. // 首次充值:金币银币切换 + 数据清理
  132. /*
  133. * 金币银币切换 GameScoreInfo 将score的数据复制到 InsureScore 把Score 字段置0 把 ScoreChange字段设置成1
  134. * 清理用户的数据
  135. * GameScoreInfo的MaxScore MaxWinscore清0
  136. * RecordUserTotalStatistics 表 数据清0
  137. * RecordUserDataStatisticsNew 表数据 清0
  138. * RecordUserGameCount 关于用户的数据删除
  139. *
  140. */
  141. try {
  142. $this->switchToInsureScoreAndCleanData($user_id);
  143. } catch (\Exception $e) {
  144. \Log::error('首次充值-金币银币切换失败', [
  145. 'user_id' => $user_id,
  146. 'error' => $e->getMessage()
  147. ]);
  148. }
  149. }
  150. //在这里更新 RecordUserTotalStatistics 数据 将LastRechargeValue字段更新为payAmt 如果不存在则插入
  151. DB::connection('write')->table('QPRecordDB.dbo.RecordUserTotalStatistics')
  152. ->updateOrInsert(['UserID' => $user_id], ['LastRechargeValue' => $payAmt]);
  153. }
  154. if ($Recharge > 0) {
  155. // 添加日志记录表
  156. StoredProcedure::addPlatformData($user_id, 3, $Recharge * NumConfig::NUM_VALUE);
  157. // 增加用户金币变化记录
  158. $AfterScore = RecordScoreInfo::addScore($user_id, ($Recharge * NumConfig::NUM_VALUE), $czReason); #充值
  159. if ($AfterScore) {
  160. RecordScoreInfo::addScore($user_id, ($give * NumConfig::NUM_VALUE), $cjReason, $AfterScore); #赠送彩金
  161. }
  162. }
  163. $favorable_price = (int) round($favorable_price * NumConfig::NUM_VALUE);
  164. $firstScore = DB::connection('write')->table('QPTreasureDB.dbo.GameScoreInfo')->where('UserID', $user_id)->value('Score');
  165. $Score = $favorable_price + $firstScore;
  166. if ($payAmt > 0) {
  167. try {
  168. $userInfo = DB::table(TableName::QPAccountsDB() . 'AccountsInfo')
  169. ->where('UserID', $user_id)
  170. ->first();
  171. $channelConfig = DB::table('QPPlatformDB.dbo.ChannelPackageName')->where('Channel', $userInfo->Channel)->first();
  172. // Util::WriteLog('xxxxx', [$userInfo->Channel, $channelConfig, $query, $firstScore, $channelConfig->Rate > 0 && $channelConfig->ContrlScore > 0, $channelConfig->MinScore * NumConfig::NUM_VALUE > $firstScore]);
  173. if ($channelConfig && !$query && false) {
  174. if ($channelConfig->Rate > 0 && $channelConfig->ContrlScore > 0) {
  175. if ($channelConfig->MinScore * NumConfig::NUM_VALUE >= $firstScore) {
  176. $openGames = config('games.openKGame');
  177. $query = DB::table('QPTreasureDB.dbo.UserScoreControl')->where('UserID', $user_id)->first();
  178. if (!$query) {
  179. $build_sql = DB::connection('write')->table('QPTreasureDB.dbo.UserScoreControl');
  180. //Util::WriteLog('control_old_user',$list);
  181. $data = [
  182. 'ControlScore' => (int)($channelConfig->ContrlScore * NumConfig::NUM_VALUE),
  183. 'EffectiveScore' => 0,
  184. 'ControlKindID' => -1,
  185. 'Remarks' => '',
  186. 'InsertDate' => date('Y-m-d H:i:s'),
  187. 'ControlRadian' => 0
  188. ];
  189. $build_sql->updateOrInsert(['UserID' => $user_id], $data);
  190. foreach ($openGames as $GameID) {
  191. $KindData = [
  192. 'UserID' => $user_id,
  193. 'KindID' => $GameID,
  194. 'ControlRadian' => $channelConfig->Rate,
  195. 'ControlDate' => date('Y-m-d H:i:s')
  196. ];
  197. DB::connection('write')->table('QPTreasureDB.dbo.UserControlKind')->updateOrInsert(['UserID' => $user_id, 'KindID' => $GameID], $KindData);
  198. }
  199. }
  200. }
  201. }
  202. }
  203. } catch (\Exception $exception) {
  204. }
  205. // 记录订单变化后金币
  206. DB::connection('write')->table('agent.dbo.order')
  207. ->where('order_sn', $order_sn)
  208. ->update(['after_amount' => $Score]);
  209. // 增加用户充值变化值
  210. RecordUserDataStatistics::updateOrAdd($user_id, 0, $payAmt);
  211. }
  212. // 不是周卡的时候执行
  213. if ($GiftsID < 100 || $GiftsID >= 200) {
  214. // 增加用户金币
  215. DB::connection('write')->table('QPTreasureDB.dbo.GameScoreInfo')->where('UserID', $user_id)->increment('Score', $favorable_price);
  216. }
  217. // 充值推广佣金
  218. // (new AgentUser())->reward($user_id, $payAmt, $order_sn);
  219. //
  220. // 周卡 -- 执行存储过程
  221. if (isset($GiftsID) && $GiftsID > 100 && $GiftsID < 200) {
  222. $CardID = (int)$GiftsID - 100;
  223. StoredProcedure::BuyMonthCard($user_id, $CardID, $order_sn);
  224. // 开始执行时间
  225. $startTime = Helper::millisecond();
  226. Log::info('GSP_GP_BuyMonthCard 执行时间:' . ((Helper::millisecond() - $startTime) / 1000));
  227. }
  228. //设置第二天要领取
  229. if (isset($GiftsID) && $GiftsID >= 200 && $GiftsID < 300 ) {
  230. $first = DB::table('agent.dbo.recharge_gear')->where('gift_id', $GiftsID)->select('gift_id', 'money', 'give', 'favorable_price', 'second_give')->first();
  231. if ($first && $first->second_give > 0) {
  232. $fpkey = 'Firstpay_' . $user_id;
  233. $data = (array)$first;
  234. $data['buytime'] = time();
  235. $data['czReason'] = $czReason;
  236. $data['cjReason'] = $cjReason;
  237. Redis::set($fpkey, json_encode($data));
  238. DB::table(TableName::agent() . 'guide_payment')->updateOrInsert([
  239. 'UserID' => $user_id,
  240. 'GiftID' => $GiftsID,
  241. 'CreateTime' => now()
  242. ], ['UserID' => $user_id]);
  243. }
  244. }
  245. //设置第二天要领取
  246. if (!empty($GiftsID) && $GiftsID >= 300 && $GiftsID < 400 ) {
  247. Redis::del('repay_temp_'.$user_id);
  248. }
  249. // 数据统计后台 -- 充值记录添加
  250. (new RechargeWithDraw())->recharge($user_id, $payAmt);
  251. // (new RechargeWithDraw())->recharge($user_id, $Recharge);
  252. if ($AdId && $payAmt) AfEvent::dispatch([$user_id, $payAmt, $AdId, $eventType]);
  253. try {
  254. //新邀请
  255. (new AgentController())->processDeposit($user_id, $payAmt,$order_sn);
  256. // AgentService::recordPerformance($user_id, $payAmt * NumConfig::NUM_VALUE);
  257. } catch (\Exception $exception) {
  258. Util::WriteLog("AgentService", $exception->getTraceAsString());
  259. }
  260. return [$Score];
  261. }
  262. /**
  263. * 执行存储过程
  264. * @param $user_id
  265. * @param $payAmt
  266. * @param $favorable_price
  267. * @param $Score
  268. * @param $GiftsID
  269. */
  270. public function storedProcedure($user_id, $payAmt, $favorable_price, $Score, $GiftsID)
  271. {
  272. // 开始执行时间
  273. $startTime = Helper::millisecond();
  274. // 执行存储过程 -- 防刷机制
  275. StoredProcedure::SetUserTabType($user_id);
  276. Log::info('GSP_GP_SetUserTabType12 执行时间:' . ((Helper::millisecond() - $startTime) / 1000));
  277. # 单控标签 -- 执行存储过程
  278. StoredProcedure::user_label($user_id, 1, $payAmt);
  279. Log::info('CheckAccountsLabel 执行时间:' . ((Helper::millisecond() - $startTime) / 1000));
  280. // 服务器通知
  281. // $url = config('transfer.stock')['url'] . 'notifyPay';
  282. // Log::info('中转服参数 ' . json_encode([
  283. // 'userid' => $user_id, 'getScore' => $favorable_price, 'score' => $Score,
  284. // 'giftsid' => empty($GiftsID) ? 0 : $GiftsID,
  285. // 'url' => $url
  286. // ]));
  287. // $res = (new HttpCurl())->service($url, ['userid' => $user_id, 'getScore' => $favorable_price, 'score' => $Score, 'giftsid' => empty($GiftsID) ? 0 : $GiftsID]);
  288. //
  289. // Log::info('中转服 执行时间:' . ((Helper::millisecond() - $startTime) / 1000), [
  290. // 'res' => $res,
  291. // ]);
  292. // AF 事件
  293. // (new AppflyerEvent())->event($user_id, '', 'af_purchase_new', $payAmt);
  294. // Log::info('AF 执行时间:' . ((Helper::millisecond() - $startTime) / 1000));
  295. }
  296. /**
  297. * 首次充值:金币银币切换 + 数据清理
  298. * @param int $user_id 用户ID
  299. */
  300. private function switchToInsureScoreAndCleanData($user_id)
  301. {
  302. \Log::info('开始执行金币银币切换', ['user_id' => $user_id]);
  303. try {
  304. // 1. GameScoreInfo: 将Score的数据复制到InsureScore,把Score字段置0,把ScoreChange字段设置成1
  305. $scoreInfo = DB::connection('write')->table('QPTreasureDB.dbo.GameScoreInfo')
  306. ->where('UserID', $user_id)
  307. ->first();
  308. if ($scoreInfo) {
  309. DB::connection('write')->table('QPTreasureDB.dbo.GameScoreInfo')
  310. ->where('UserID', $user_id)
  311. ->update([
  312. 'InsureScore' => max($scoreInfo->Score,40), // 将Score复制到InsureScore
  313. 'Score' => 0, // Score置0
  314. 'ScoreChange' => 1, // ScoreChange设置成1
  315. 'MaxScore' => 0, // MaxScore清0
  316. 'MaxWinScore' => 0 // MaxWinScore清0
  317. ]);
  318. \Log::info('GameScoreInfo切换成功', [
  319. 'user_id' => $user_id,
  320. 'original_score' => $scoreInfo->Score,
  321. 'insure_score' => $scoreInfo->Score
  322. ]);
  323. }
  324. // 2. RecordUserTotalStatistics 表数据清0
  325. $totalStats = DB::connection('write')->table('QPRecordDB.dbo.RecordUserTotalStatistics')
  326. ->where('UserID', $user_id)
  327. ->first();
  328. if ($totalStats) {
  329. DB::connection('write')->table('QPRecordDB.dbo.RecordUserTotalStatistics')
  330. ->where('UserID', $user_id)
  331. ->update([
  332. 'Winning' => 0,
  333. 'LostInning' => 0,
  334. 'Revenue' => 0,
  335. 'WinScore' => 0,
  336. 'LostScore' => 0,
  337. 'Handsel' => 0,
  338. 'DrawBase' => 0,
  339. 'TotalBet' => 0,
  340. 'TotalScore' => 0,
  341. 'MaxDrawBase' => 0,
  342. 'MaxScore' => 0,
  343. 'MaxWinScore' => 0,
  344. 'Rounds' => 0,
  345. 'ProtectedRounds' => 0
  346. ]);
  347. \Log::info('RecordUserTotalStatistics清0成功', ['user_id' => $user_id]);
  348. }
  349. // 3. RecordUserDataStatisticsNew 表数据清0
  350. DB::connection('write')->table('QPRecordDB.dbo.RecordUserDataStatisticsNew')
  351. ->where('UserID', $user_id)
  352. ->delete();
  353. \Log::info('RecordUserDataStatisticsNew清0成功', ['user_id' => $user_id]);
  354. // 4. RecordUserGameCount 关于用户的数据删除
  355. DB::connection('write')->table('QPRecordDB.dbo.RecordUserGameCount')
  356. ->where('UserID', $user_id)
  357. ->delete();
  358. \Log::info('RecordUserGameCount清除成功', ['user_id' => $user_id]);
  359. \Log::info('金币银币切换完成', [
  360. 'user_id' => $user_id,
  361. 'insure_score' => $scoreInfo->Score ?? 0
  362. ]);
  363. } catch (\Exception $e) {
  364. \Log::error('金币银币切换异常', [
  365. 'user_id' => $user_id,
  366. 'error' => $e->getMessage(),
  367. 'trace' => $e->getTraceAsString()
  368. ]);
  369. throw $e;
  370. }
  371. }
  372. /**
  373. * 创建首充礼包记录
  374. */
  375. public function createFirstPayGiftRecord($user_id, $gift_id, $payAmt)
  376. {
  377. // 检查是否已有记录
  378. $existing = DB::connection('write')->table('agent.dbo.first_pay_gift_records')
  379. ->where('user_id', $user_id)
  380. ->first();
  381. if ($existing) {
  382. \Log::info('首充礼包记录已存在', ['user_id' => $user_id]);
  383. return;
  384. }
  385. // 获取礼包配置
  386. $giftConfig = DB::connection('write')->table('agent.dbo.recharge_gift')
  387. ->where('gift_id', $gift_id)
  388. ->first();
  389. if (!$giftConfig) {
  390. \Log::error('首充礼包配置不存在', ['gift_id' => $gift_id]);
  391. return;
  392. }
  393. // 计算金额
  394. $totalBonusAmount = round($giftConfig->total_bonus * $payAmt / 100, 2);
  395. $bonusInstantlyAmount = round($giftConfig->bonus_instantly * $payAmt / 100, 2);
  396. // 解析JSON数据
  397. $dayRewards = $giftConfig->day_rewards ? json_decode($giftConfig->day_rewards, true) : null;
  398. $bettingBonus = $giftConfig->betting_bonus ? json_decode($giftConfig->betting_bonus, true) : null;
  399. $bettingTask = $giftConfig->betting_task ? json_decode($giftConfig->betting_task, true) : null;
  400. // 计算各部分金额
  401. $dayRewardsTotal = $dayRewards ? round($dayRewards['total_bonus'] * $payAmt / 100, 2) : 0;
  402. $bettingBonusTotal = $bettingBonus ? round($bettingBonus['total_bonus'] * $payAmt / 100, 2) : 0;
  403. $bettingTaskTotal = $bettingTask ? round($bettingTask['total_bonus'] * $payAmt / 100, 2) : 0;
  404. // 创建记录
  405. $data = [
  406. 'user_id' => $user_id,
  407. 'gift_id' => $gift_id,
  408. 'pay_amount' => $payAmt,
  409. 'total_bonus' => $totalBonusAmount,
  410. 'bonus_instantly' => $bonusInstantlyAmount,
  411. 'gift_name' => $giftConfig->gift_name,
  412. // 每日奖励
  413. 'day_rewards_total' => $dayRewardsTotal,
  414. 'day_rewards_claimed' => 0,
  415. 'day_rewards_data' => $giftConfig->day_rewards,
  416. 'day_last_claim_date' => null,
  417. // 下注奖励
  418. 'betting_bonus_total' => $bettingBonusTotal,
  419. 'betting_bonus_claimed' => 0,
  420. 'betting_bonus_data' => $giftConfig->betting_bonus,
  421. 'betting_current_bet' => 0,
  422. // 下注任务
  423. 'betting_task_total' => $bettingTaskTotal,
  424. 'betting_task_claimed' => 0,
  425. 'betting_task_data' => $giftConfig->betting_task,
  426. 'created_at' => date('Y-m-d H:i:s'),
  427. 'updated_at' => date('Y-m-d H:i:s')
  428. ];
  429. DB::connection('write')->table('agent.dbo.first_pay_gift_records')->insert($data);
  430. \Log::info('首充礼包记录创建成功', [
  431. 'user_id' => $user_id,
  432. 'gift_id' => $gift_id,
  433. 'pay_amount' => $payAmt,
  434. 'total_bonus' => $totalBonusAmount
  435. ]);
  436. }
  437. }