OrderServices.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890
  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\Services\HolidayWheelService;
  16. use App\Events\OrderPaid;
  17. use App\Util;
  18. use Illuminate\Support\Facades\DB;
  19. use Illuminate\Support\Facades\Log;
  20. use Illuminate\Support\Facades\Redis;
  21. class OrderServices
  22. {
  23. public $FirstCharge = 30;
  24. public $FirstChargeGive = 20;
  25. public $FirstGiftID = 301;
  26. private $first_pay = null;
  27. public function __construct()
  28. {
  29. }
  30. /**
  31. * 获取支付金额
  32. * @param int $GiftsID 礼包ID
  33. * @param int $user_id 用户ID
  34. * @param int $payAmt 支付金额(元)
  35. * @return array|void [$give, $favorable_price, $Recharge, $czReason, $cjReason] 赠送金额,赠送金额+充值金额,充值金额,充值原因,彩金原因
  36. */
  37. public function getPayInfo($GiftsID, $user_id, $payAmt)
  38. {
  39. $give = $czReason = $cjReason = $Recharge = $favorable_price = $second_give = 0;
  40. $shouldCreateGiftRecord = false; // 是否需要创建首充礼包记录
  41. // 判断是不是首冲礼包
  42. if (!empty($GiftsID)) {
  43. if ($GiftsID == 301) { // 礼包--首冲
  44. // 检查用户是否已购买过首充礼包
  45. $hasPurchased = DB::connection('write')->table('agent.dbo.first_pay_gift_records')
  46. ->where('user_id', $user_id)
  47. ->exists();
  48. if ($hasPurchased) {
  49. // 已购买首充礼包,走普通充值逻辑(只加本金)
  50. $Recharge = $payAmt;
  51. $give = 0;
  52. $favorable_price = $Recharge + $give;
  53. $czReason = 1;
  54. $cjReason = 45;
  55. } else {
  56. // 首次购买首充礼包,走赠送逻辑(立即获得bonus_instantly%)
  57. $Gifts = DB::connection('write')->table('agent.dbo.recharge_gift')->where('gift_id', $GiftsID)->first();
  58. $favorable_price = round($Gifts->bonus_instantly*$payAmt/100,2);
  59. $give = $favorable_price-$payAmt;
  60. $Recharge = $payAmt;
  61. $czReason = 50;
  62. $cjReason = 51;
  63. // 创建首充礼包记录
  64. try {
  65. $this->createFirstPayGiftRecord($user_id, $GiftsID, $payAmt);
  66. } catch (\Exception $e) {
  67. \Log::error('首充礼包记录创建失败', [
  68. 'user_id' => $user_id,
  69. 'gift_id' => $GiftsID,
  70. 'error' => $e->getMessage()
  71. ]);
  72. }
  73. }
  74. } else if ($GiftsID == 302) { // 破产礼包
  75. // 检查用户今日是否已充值过破产礼包
  76. $todayRecharge = DB::connection('write')->table('agent.dbo.order')
  77. ->where('user_id', $user_id)
  78. ->where('GiftsID', 302)
  79. ->where('pay_status', 1)
  80. ->whereDate('created_at', date('Y-m-d'))
  81. ->first();
  82. // 今日首次购买破产礼包,走赠送逻辑
  83. $Gifts = DB::connection('write')->table('agent.dbo.recharge_gift')->where('gift_id', $GiftsID)->where('recommend', $payAmt)->first();
  84. if($Gifts && !$todayRecharge){
  85. $favorable_price = round($Gifts->bonus_instantly*$payAmt/100,2);
  86. $give = $favorable_price-$payAmt;
  87. $Recharge = $payAmt;
  88. $czReason = 50;
  89. $cjReason = 51;
  90. }else{
  91. $Recharge = $payAmt;
  92. $give = 0;
  93. $favorable_price = $Recharge + $give;
  94. $czReason = 1;
  95. $cjReason = 45;
  96. }
  97. }else if ($GiftsID == 303) { // 每日首充礼包
  98. // 检查用户今日是否已充值过每日首充礼包
  99. $todayStart = date('Y-m-d') . ' 00:00:00';
  100. $todayEnd = date('Y-m-d') . ' 23:59:59';
  101. $todayRecharge = DB::connection('write')->table('agent.dbo.order')
  102. ->where('user_id', $user_id)
  103. ->where('GiftsID', 303)
  104. ->where('pay_status', 1)
  105. ->where('pay_at', '>=', $todayStart)
  106. ->where('pay_at', '<=', $todayEnd)
  107. ->first();
  108. if ($todayRecharge) {
  109. // 今日已充值过,只发放本金(不发放奖励)
  110. $Recharge = $payAmt;
  111. $give = 0;
  112. $favorable_price = $Recharge + $give;
  113. $czReason = 1;
  114. $cjReason = 45;
  115. } else {
  116. // 今日未充值过,按照礼包配置的比例发放
  117. $Gifts = DB::connection('write')->table('agent.dbo.recharge_gift')
  118. ->where('gift_id', $GiftsID)
  119. ->where('recommend', $payAmt)
  120. ->first();
  121. if($Gifts){
  122. $favorable_price = round($Gifts->bonus_instantly*$payAmt/100,2);
  123. $give = $favorable_price-$payAmt;
  124. $Recharge = $payAmt;
  125. $czReason = 50;
  126. $cjReason = 51;
  127. }else{
  128. // 如果没有找到对应的礼包配置,按照普通充值处理
  129. $Recharge = $payAmt;
  130. $give = 0;
  131. $favorable_price = $Recharge + $give;
  132. $czReason = 1;
  133. $cjReason = 45;
  134. }
  135. }
  136. }else if ($GiftsID == 304) { // 每日礼包(三档充值)
  137. // 检查用户今日是否已充值过该档位的每日礼包
  138. $todayStart = date('Y-m-d') . ' 00:00:00';
  139. $todayEnd = date('Y-m-d') . ' 23:59:59';
  140. $todayRecharge = DB::connection('write')->table('agent.dbo.order')
  141. ->where('user_id', $user_id)
  142. ->where('GiftsID', 304)
  143. ->where('amount', $payAmt) // 检查该档位金额
  144. ->where('pay_status', 1)
  145. ->where('pay_at', '>=', $todayStart)
  146. ->where('pay_at', '<=', $todayEnd)
  147. ->first();
  148. if ($todayRecharge) {
  149. // 今日已充值过该档位,只发放本金(不发放奖励)
  150. $Recharge = $payAmt;
  151. $give = 0;
  152. $favorable_price = $Recharge + $give;
  153. $czReason = 1;
  154. $cjReason = 45;
  155. } else {
  156. // 今日未充值过该档位,按照礼包配置的比例发放
  157. $Gifts = DB::connection('write')->table('agent.dbo.recharge_gift')
  158. ->where('gift_id', $GiftsID)
  159. ->where('recommend', $payAmt)
  160. ->first();
  161. if($Gifts){
  162. $favorable_price = round($Gifts->bonus_instantly*$payAmt/100,2);
  163. $give = $favorable_price-$payAmt;
  164. $Recharge = $payAmt;
  165. $czReason = 50;
  166. $cjReason = 51;
  167. }else{
  168. // 如果没有找到对应的礼包配置,按照普通充值处理
  169. $Recharge = $payAmt;
  170. $give = 0;
  171. $favorable_price = $Recharge + $give;
  172. $czReason = 1;
  173. $cjReason = 45;
  174. }
  175. }
  176. }else if ($GiftsID == 305) { // 连续未充值 VIP 新礼包
  177. // 305 改为按“轮次”判断:上一轮过期后可再次充值并获得新一轮奖励
  178. $latestRecord = DB::connection('write')->table('agent.dbo.inactive_vip_gift_records')
  179. ->where('user_id', $user_id)
  180. ->where('gift_id', 305)
  181. ->orderBy('id', 'desc')
  182. ->first();
  183. // 有记录:根据是否领满7天判断状态
  184. $allClaimedMask = (1 << 7) - 1;
  185. $canStartNewRound = !$latestRecord || ((($latestRecord->claimed_days_mask & $allClaimedMask) == $allClaimedMask));
  186. if (!$canStartNewRound) {
  187. // 当前轮次未过期:只发放本金(不发放奖励)
  188. $Recharge = $payAmt;
  189. $give = 0;
  190. $favorable_price = $Recharge + $give;
  191. $czReason = 1;
  192. $cjReason = 45;
  193. } else {
  194. // 开启新一轮 305:无立即奖励,全部奖励通过 7 天签到领取
  195. $Recharge = $payAmt;
  196. $give = 0;
  197. $favorable_price = $payAmt;
  198. $czReason = 50;
  199. $cjReason = 51;
  200. // 确定奖励百分比
  201. $bonusPercent = 100;
  202. $stat = DB::connection('write')->table('QPRecordDB.dbo.RecordUserTotalStatistics')
  203. ->where('UserID', $user_id)
  204. ->select('Recharge', 'RechargeTimes')
  205. ->first();
  206. $totalRecharge = (float)($stat->Recharge ?? 0);
  207. $rechargeTimes = (int)($stat->RechargeTimes ?? 0);
  208. if ($rechargeTimes > 0) {
  209. $avgRecharge = $totalRecharge / $rechargeTimes;
  210. $tiers = $this->getRecallGiftTiers($avgRecharge);
  211. foreach ($tiers as $tier) {
  212. if ((float)$tier['amount'] == (float)$payAmt) {
  213. $bonusPercent = $tier['bonus_percent'];
  214. break;
  215. }
  216. }
  217. }
  218. $this->createInactiveVipGiftRecord($user_id, $payAmt, $bonusPercent);
  219. }
  220. } else if ($GiftsID == 306) { // free bonus礼包
  221. $Recharge = $payAmt;
  222. $give = 0;
  223. $favorable_price = $Recharge + $give;
  224. $czReason = 50;
  225. $cjReason = 51;
  226. } else if ($GiftsID > 400) {
  227. $Status = 1;
  228. $recharge_gear = DB::connection('write')->table('agent.dbo.recharge_gear')->where('status', $Status)->where('money', $payAmt)->select('favorable_price', 'give')->first();
  229. if(!$recharge_gear){
  230. $Recharge=$payAmt;
  231. $give=0;
  232. }else{
  233. $Recharge = $recharge_gear->favorable_price;
  234. $give = $recharge_gear->give;
  235. }
  236. $favorable_price = $Recharge + $give;
  237. $czReason = 1;
  238. $cjReason = 45;
  239. }
  240. } else { // 普通订单
  241. $Status = 1;
  242. $recharge_gear = DB::connection('write')->table('agent.dbo.recharge_gear')->where('status', $Status)->where('money', $payAmt)->select('favorable_price', 'give')->first();
  243. if(!$recharge_gear){
  244. $Recharge=$payAmt;
  245. $give=0;
  246. }else{
  247. $Recharge = $recharge_gear->favorable_price;
  248. $give = $recharge_gear->give;
  249. }
  250. $favorable_price = $Recharge + $give;
  251. $czReason = 1;
  252. $cjReason = 45;
  253. }
  254. return [$give, $favorable_price, $Recharge, $czReason, $cjReason, $second_give];
  255. }
  256. /**
  257. * 添加玩家充值记录
  258. * @param $user_id
  259. * @param $payAmt
  260. * @param $favorable_price
  261. * @param $order_sn
  262. * @param $GiftsID
  263. * @param $Recharge
  264. * @param $czReason
  265. * @param $give
  266. * @param $cjReason
  267. * @param $AdId
  268. * @param $eventType
  269. * @param mixed $fee 支付手续费
  270. */
  271. public function addRecord($user_id, $payAmt, $favorable_price, $order_sn, $GiftsID, $Recharge, $czReason, $give, $cjReason, $AdId, $eventType, $fee = 0)
  272. {
  273. if ($payAmt > 0) {
  274. // 增加玩家充值金额
  275. $query = DB::connection('write')->table('QPAccountsDB.dbo.YN_VIPAccount')
  276. ->where('UserID', $user_id)
  277. ->value('Recharge');
  278. if ($query) {
  279. DB::connection('write')->table('QPAccountsDB.dbo.YN_VIPAccount')
  280. ->where('UserID', $user_id)
  281. ->increment('Recharge', $payAmt);
  282. } else {
  283. DB::connection('write')->table('QPAccountsDB.dbo.YN_VIPAccount')
  284. ->where('UserID', $user_id)
  285. ->insert(['Recharge' => $payAmt, 'UserID' => $user_id]);
  286. // 首次充值:金币银币切换 + 数据清理
  287. /*
  288. * 金币银币切换 GameScoreInfo 将score的数据复制到 InsureScore 把Score 字段置0 把 ScoreChange字段设置成1
  289. * 清理用户的数据
  290. * GameScoreInfo的MaxScore MaxWinscore清0
  291. * RecordUserTotalStatistics 表 数据清0
  292. * RecordUserDataStatisticsNew 表数据 清0
  293. * RecordUserGameCount 关于用户的数据删除
  294. *
  295. */
  296. try {
  297. $this->switchToInsureScoreAndCleanData($user_id);
  298. } catch (\Exception $e) {
  299. \Log::error('首次充值-金币银币切换失败', [
  300. 'user_id' => $user_id,
  301. 'error' => $e->getMessage()
  302. ]);
  303. }
  304. }
  305. //在这里更新 RecordUserTotalStatistics 数据 将LastRechargeValue字段更新为payAmt 如果不存在则插入
  306. DB::connection('write')->table('QPRecordDB.dbo.RecordUserTotalStatistics')
  307. ->updateOrInsert(['UserID' => $user_id], ['LastRechargeValue' => $payAmt]);
  308. // 节假日大转盘:根据充值金额增加转盘次数(首充礼包/破产礼包不计入)
  309. try {
  310. (new HolidayWheelService())->grantTimesOnRecharge($user_id, $payAmt, (int)$GiftsID);
  311. } catch (\Throwable $e) {
  312. \Log::error('holiday wheel grant times failed', [
  313. 'user_id' => $user_id,
  314. 'payAmt' => $payAmt,
  315. 'GiftsID' => $GiftsID,
  316. 'error' => $e->getMessage(),
  317. ]);
  318. }
  319. // 圣诞大转盘:根据充值金额增加转盘次数(首充礼包/破产礼包不计入)
  320. try {
  321. (new \App\Services\ChristmasWheelService())->grantTimesOnRecharge($user_id, $payAmt, (int)$GiftsID);
  322. } catch (\Throwable $e) {
  323. \Log::error('christmas wheel grant times failed', [
  324. 'user_id' => $user_id,
  325. 'payAmt' => $payAmt,
  326. 'GiftsID' => $GiftsID,
  327. 'error' => $e->getMessage(),
  328. ]);
  329. }
  330. }
  331. if ($Recharge > 0) {
  332. // 添加日志记录表
  333. StoredProcedure::addPlatformData($user_id, 3, $Recharge * NumConfig::NUM_VALUE);
  334. // 增加用户金币变化记录
  335. $AfterScore = RecordScoreInfo::addScore($user_id, ($Recharge * NumConfig::NUM_VALUE), $czReason); #充值
  336. if ($AfterScore) {
  337. RecordScoreInfo::addScore($user_id, ($give * NumConfig::NUM_VALUE), $cjReason, $AfterScore); #赠送彩金
  338. }
  339. // vip额外赠送
  340. if ($GiftsID == 0) {
  341. $userRecharge = $query ?: 0;
  342. $VIP = VipService::calculateVipLevel($user_id,$userRecharge);
  343. $level = VipService::getVipByField('VIP', $VIP);
  344. if ($level && $level->RechargeExtraSendRate > 0) {
  345. $vipSendChips = floor($Recharge * NumConfig::NUM_VALUE * ($level->RechargeExtraSendRate/100));
  346. if ($vipSendChips > 0) {
  347. RecordScoreInfo::addScore($user_id, $vipSendChips, RecordScoreInfo::REASON_VIP_SEND_CHIPS, $AfterScore);
  348. app(PaidRewardStatisticsService::class)
  349. ->incrementRecordByDateIDAndType(date('Ymd'), 'vip_recharge', $vipSendChips);
  350. }
  351. }
  352. }
  353. if (in_array($GiftsID, [0, 301, 302, 304, 305, 402]) && $give > 0) {
  354. $typeMap= [
  355. 0 => 'normal_recharge',
  356. 301 => 'first_recharge_gift',
  357. 302 => 'bankrupt_gift',
  358. 304 => 'daily_gift',
  359. 305 => 'vip_inactive_gift',
  360. 402 => 'christmas_gift',
  361. ];
  362. $type = $typeMap[intval($GiftsID)] ?? 'unknown_gift';
  363. app(PaidRewardStatisticsService::class)
  364. ->incrementRecordByDateIDAndType(date('Ymd'), $type, $give * NumConfig::NUM_VALUE);
  365. }
  366. $typeMap= [
  367. 0 => 'normal_recharge_chips',
  368. 301 => 'first_recharge_gift_chips',
  369. 302 => 'bankrupt_gift_chips',
  370. 304 => 'daily_gift_chips',
  371. 305 => 'vip_inactive_gift_chips',
  372. 306 => 'free_bonus_gift_chips',
  373. 402 => 'christmas_gift_chips',
  374. ];
  375. $type = $typeMap[intval($GiftsID)] ?? 'unknown_chips';
  376. app(PaidRewardStatisticsService::class)
  377. ->incrementRecordByDateIDAndType(date('Ymd'), $type, ($Recharge+$give) * NumConfig::NUM_VALUE);
  378. app(PaidRewardStatisticsService::class)
  379. ->incrementRecordByDateIDAndType(date('Ymd'), 'recharge_real', $Recharge * NumConfig::NUM_VALUE);
  380. }
  381. // free bonus 礼包:充值后赠送 InsureScore(单位为分)
  382. if (in_array($GiftsID, [306]) && $payAmt > 0) {
  383. $gift = DB::table('agent.dbo.recharge_gift')->lock('with(nolock)')
  384. ->where(['gift_id' => $GiftsID, 'recommend' => $Recharge])
  385. ->first();
  386. if ($gift && $gift->task_bonus > 0) {
  387. $bonus = (int) round($gift->task_bonus * NumConfig::NUM_VALUE);
  388. if ($bonus > 0) {
  389. DB::table('QPTreasureDB.dbo.GameScoreInfo')
  390. ->where('UserID', $user_id)
  391. ->increment('InsureScore', $bonus);
  392. app(PaidRewardStatisticsService::class)
  393. ->incrementRecordByDateIDAndType(date('Ymd'), 'free_bonus_gift', $give * NumConfig::NUM_VALUE);
  394. }
  395. }
  396. }
  397. $favorable_price = (int) round($favorable_price * NumConfig::NUM_VALUE) + ($vipSendChips ?? 0);
  398. $firstScore = DB::connection('write')->table('QPTreasureDB.dbo.GameScoreInfo')->where('UserID', $user_id)->value('Score');
  399. $Score = $favorable_price + $firstScore;
  400. if ($payAmt > 0) {
  401. // 记录订单变化后金币
  402. DB::connection('write')->table('agent.dbo.order')
  403. ->where('order_sn', $order_sn)
  404. ->update(['after_amount' => $Score]);
  405. // 增加用户充值变化值
  406. RecordUserDataStatistics::updateOrAdd($user_id, 0, $payAmt);
  407. }
  408. // 不是周卡的时候执行
  409. if ($GiftsID < 100 || $GiftsID >= 200) {
  410. // 增加用户金币
  411. DB::connection('write')->table('QPTreasureDB.dbo.GameScoreInfo')->where('UserID', $user_id)->increment('Score', $favorable_price);
  412. }
  413. // 充值推广佣金
  414. // (new AgentUser())->reward($user_id, $payAmt, $order_sn);
  415. //
  416. // 周卡 -- 执行存储过程
  417. // if (isset($GiftsID) && $GiftsID > 100 && $GiftsID < 200) {
  418. // $CardID = (int)$GiftsID - 100;
  419. // StoredProcedure::BuyMonthCard($user_id, $CardID, $order_sn);
  420. // // 开始执行时间
  421. // $startTime = Helper::millisecond();
  422. // Log::info('GSP_GP_BuyMonthCard 执行时间:' . ((Helper::millisecond() - $startTime) / 1000));
  423. // }
  424. //设置第二天要领取
  425. // if (isset($GiftsID) && $GiftsID >= 200 && $GiftsID < 300 ) {
  426. // $first = DB::table('agent.dbo.recharge_gear')->where('gift_id', $GiftsID)->select('gift_id', 'money', 'give', 'favorable_price', 'second_give')->first();
  427. // if ($first && $first->second_give > 0) {
  428. // $fpkey = 'Firstpay_' . $user_id;
  429. // $data = (array)$first;
  430. // $data['buytime'] = time();
  431. // $data['czReason'] = $czReason;
  432. // $data['cjReason'] = $cjReason;
  433. // Redis::set($fpkey, json_encode($data));
  434. // DB::table(TableName::agent() . 'guide_payment')->updateOrInsert([
  435. // 'UserID' => $user_id,
  436. // 'GiftID' => $GiftsID,
  437. // 'CreateTime' => now()
  438. // ], ['UserID' => $user_id]);
  439. // }
  440. // }
  441. //设置第二天要领取
  442. // if (!empty($GiftsID) && $GiftsID >= 300 && $GiftsID < 400 ) {
  443. // Redis::del('repay_temp_'.$user_id);
  444. // }
  445. // 数据统计后台 -- 充值记录添加
  446. (new RechargeWithDraw())->recharge($user_id, $payAmt, $fee);
  447. // (new RechargeWithDraw())->recharge($user_id, $Recharge);
  448. // 连续未充值 VIP 新礼包(gift_id=305)—— 充值成功后写入 7 日礼包记录(仅在首次充值时)
  449. // if (!empty($GiftsID) && (int)$GiftsID === 305 && $payAmt > 0) {
  450. // // 检查是否已经充值过305礼包,只有在首次充值时才创建7日礼包记录
  451. // $hasPurchased305 = DB::connection('write')->table('agent.dbo.order')
  452. // ->where('user_id', $user_id)
  453. // ->where('GiftsID', 305)
  454. // ->where('pay_status', 1)
  455. //// ->where('order_sn', '!=', $order_sn) // 排除当前订单
  456. // ->exists();
  457. //
  458. // if (!$hasPurchased305) {
  459. // // 首次充值,创建7日礼包记录
  460. // try {
  461. // $this->createInactiveVipGiftRecord($user_id, $payAmt);
  462. // } catch (\Exception $e) {
  463. // \Log::error('inactive vip gift record create failed', [
  464. // 'user_id' => $user_id,
  465. // 'payAmt' => $payAmt,
  466. // 'error' => $e->getMessage(),
  467. // ]);
  468. // }
  469. // }
  470. // }
  471. // if ($AdId && $payAmt) AfEvent::dispatch([$user_id, $payAmt, $AdId, $eventType]);
  472. try {
  473. //新邀请
  474. //(new AgentController())->processDeposit($user_id, $payAmt,$order_sn);
  475. AgentService::recordPerformance($user_id, $payAmt * NumConfig::NUM_VALUE);
  476. } catch (\Exception $exception) {
  477. Util::WriteLog("AgentService", $exception->getTraceAsString());
  478. }
  479. // 触发订单支付完成事件(优惠券处理等由 Listener 负责)
  480. try {
  481. event(new OrderPaid($user_id, $payAmt, $order_sn));
  482. } catch (\Exception $e) {
  483. \Log::error('OrderPaid event dispatch failed', [
  484. 'user_id' => $user_id,
  485. 'payAmt' => $payAmt,
  486. 'order_sn' => $order_sn,
  487. 'error' => $e->getMessage(),
  488. ]);
  489. }
  490. return [$Score];
  491. }
  492. /**
  493. * 执行存储过程
  494. * @param $user_id
  495. * @param $payAmt
  496. * @param $favorable_price
  497. * @param $Score
  498. * @param $GiftsID
  499. */
  500. public function storedProcedure($user_id, $payAmt, $favorable_price, $Score, $GiftsID)
  501. {
  502. // 开始执行时间
  503. $startTime = Helper::millisecond();
  504. // 执行存储过程 -- 防刷机制
  505. StoredProcedure::SetUserTabType($user_id);
  506. Log::info('GSP_GP_SetUserTabType12 执行时间:' . ((Helper::millisecond() - $startTime) / 1000));
  507. # 单控标签 -- 执行存储过程
  508. StoredProcedure::user_label($user_id, 1, $payAmt);
  509. Log::info('CheckAccountsLabel 执行时间:' . ((Helper::millisecond() - $startTime) / 1000));
  510. // 服务器通知
  511. // $url = config('transfer.stock')['url'] . 'notifyPay';
  512. // Log::info('中转服参数 ' . json_encode([
  513. // 'userid' => $user_id, 'getScore' => $favorable_price, 'score' => $Score,
  514. // 'giftsid' => empty($GiftsID) ? 0 : $GiftsID,
  515. // 'url' => $url
  516. // ]));
  517. // $res = (new HttpCurl())->service($url, ['userid' => $user_id, 'getScore' => $favorable_price, 'score' => $Score, 'giftsid' => empty($GiftsID) ? 0 : $GiftsID]);
  518. //
  519. // Log::info('中转服 执行时间:' . ((Helper::millisecond() - $startTime) / 1000), [
  520. // 'res' => $res,
  521. // ]);
  522. // AF 事件
  523. // (new AppflyerEvent())->event($user_id, '', 'af_purchase_new', $payAmt);
  524. // Log::info('AF 执行时间:' . ((Helper::millisecond() - $startTime) / 1000));
  525. }
  526. /**
  527. * 首次充值:金币银币切换 + 数据清理
  528. * @param int $user_id 用户ID
  529. */
  530. private function switchToInsureScoreAndCleanData($user_id)
  531. {
  532. \Log::info('开始执行金币银币切换', ['user_id' => $user_id]);
  533. try {
  534. // 1. GameScoreInfo: 将Score的数据复制到InsureScore,把Score字段置0,把ScoreChange字段设置成1
  535. $scoreInfo = DB::connection('write')->table('QPTreasureDB.dbo.GameScoreInfo')
  536. ->where('UserID', $user_id)
  537. ->first();
  538. $freeSecond = 0;
  539. if ($scoreInfo) {
  540. DB::connection('write')->table('QPTreasureDB.dbo.GameScoreInfo')
  541. ->where('UserID', $user_id)
  542. ->update([
  543. 'InsureScore' => max($scoreInfo->Score,10000), // 将Score复制到InsureScore
  544. 'Score' => 0, // Score置0
  545. 'ScoreChange' => 1, // ScoreChange设置成1
  546. 'MaxScore' => 0, // MaxScore清0
  547. 'MaxWinScore' => 0, // MaxWinScore清0
  548. 'PlayTimeCount' => 0, //重置游戏时间
  549. 'OnLineTimeCount' => $scoreInfo->PlayTimeCount, //赋值免费游戏时间
  550. ]);
  551. $freeSecond = $scoreInfo->PlayTimeCount;
  552. //TODO
  553. \Log::info('GameScoreInfo切换成功', [
  554. 'user_id' => $user_id,
  555. 'original_score' => $scoreInfo->Score,
  556. 'insure_score' => $scoreInfo->Score
  557. ]);
  558. }
  559. // 2. RecordUserTotalStatistics 表数据清0
  560. $totalStats = DB::connection('write')->table('QPRecordDB.dbo.RecordUserTotalStatistics')
  561. ->where('UserID', $user_id)
  562. ->first();
  563. if ($totalStats) {
  564. DB::connection('write')->table('QPRecordDB.dbo.RecordUserTotalStatistics')
  565. ->where('UserID', $user_id)
  566. ->update([
  567. 'WinInning' => 0,
  568. 'LostInning' => 0,
  569. 'Revenue' => 0,
  570. 'WinScore' => 0,
  571. 'LostScore' => 0,
  572. 'Handsel' => 0,
  573. 'DrawBase' => 0,
  574. 'TotalBet' => 0,
  575. // 'TotalScore' => 0,
  576. 'MaxDrawBase' => 0,
  577. 'MaxScore' => 0,
  578. 'MaxWinScore' => 0,
  579. 'Rounds' => 0,
  580. 'ProtectedRounds' => 0
  581. ]);
  582. \Log::info('RecordUserTotalStatistics清0成功', ['user_id' => $user_id]);
  583. }
  584. // 3. RecordUserDataStatisticsNew 表数据清0
  585. DB::connection('write')->table('QPRecordDB.dbo.RecordUserDataStatisticsNew')
  586. ->where('UserID', $user_id)
  587. ->delete();
  588. \Log::info('RecordUserDataStatisticsNew清0成功', ['user_id' => $user_id]);
  589. $freeCount = DB::connection('read')->table(TableName::QPRecordDB() . 'RecordUserGameCount')
  590. ->where('UserID', $user_id)
  591. ->sum('Cnt');
  592. // 4. RecordUserGameCount 关于用户的数据删除
  593. DB::connection('write')->table('QPRecordDB.dbo.RecordUserGameCount')
  594. ->where('UserID', $user_id)
  595. ->delete();
  596. DB::connection('write')->table('QPRecordDB.dbo.RecordUserGameDayCount')
  597. ->where('UserID', $user_id)
  598. ->delete();
  599. $userModel = GlobalUserInfo::getGameUserInfo('UserID', $user_id);
  600. if ($userModel && $userModel->RegisterDate){
  601. $RecordPlatformDataModel = new \App\Models\RecordPlatformData();
  602. $RecordPlatformDataModel->UpdateFreeGameTime($userModel->Channel,$userModel->RegisterDate,$freeSecond,$freeCount);
  603. }
  604. \Log::info('RecordUserGameCount清除成功', ['user_id' => $user_id]);
  605. \Log::info('金币银币切换完成', [
  606. 'user_id' => $user_id,
  607. 'insure_score' => $scoreInfo->Score ?? 0
  608. ]);
  609. } catch (\Exception $e) {
  610. \Log::error('金币银币切换异常', [
  611. 'user_id' => $user_id,
  612. 'error' => $e->getMessage(),
  613. 'trace' => $e->getTraceAsString()
  614. ]);
  615. throw $e;
  616. }
  617. }
  618. /**
  619. * 获取召回礼包(gift_id=305)三档金额及对应奖励百分比
  620. * 可用档位:9.99, 19.99, 29.99, 39.99, 49.99, 59.99, 79.99, 99.99
  621. * 初档 100% 加成,后续每档增加 15%
  622. * @param float $avgRecharge 用户平均充值金额
  623. * @return array [['amount'=>float, 'bonus_percent'=>int], ...] 三档信息
  624. */
  625. private function getRecallGiftTiers($avgRecharge)
  626. {
  627. $amounts = [9.99, 19.99, 29.99, 39.99, 49.99, 59.99, 79.99, 99.99];
  628. $bonusPercents = [100, 115, 130];
  629. $index = count($amounts);
  630. foreach ($amounts as $i => $amt) {
  631. if ($avgRecharge <= $amt) {
  632. $index = $i;
  633. break;
  634. }
  635. }
  636. if ($index > count($amounts) - 3) {
  637. $index = count($amounts) - 3;
  638. }
  639. $tiers = [];
  640. for ($i = 0; $i < 3; $i++) {
  641. $tiers[] = [
  642. 'amount' => $amounts[$index + $i],
  643. 'bonus_percent' => $bonusPercents[$i],
  644. ];
  645. }
  646. return $tiers;
  647. }
  648. /**
  649. * 召回礼包(gift_id=305)—— 创建 7 日签到礼包记录
  650. * @param int $user_id
  651. * @param float $payAmt 本次充值金额(元)
  652. * @param int $bonusPercent 奖励百分比(70/85/100)
  653. */
  654. private function createInactiveVipGiftRecord($user_id, $payAmt, $bonusPercent = 70)
  655. {
  656. // 获取上一次充值订单
  657. $prevOrder = DB::connection('write')->table('agent.dbo.order')
  658. ->where('user_id', $user_id)
  659. ->where('pay_status', 1)
  660. ->where('GiftsID', '!=', 305)
  661. ->orderBy('pay_at', 'desc')
  662. ->first();
  663. $inactiveDays = 7;
  664. if ($prevOrder) {
  665. $prevDate = date('Y-m-d', strtotime($prevOrder->pay_at));
  666. $today = date('Y-m-d');
  667. $diffDays = (strtotime($today) - strtotime($prevDate)) / 86400;
  668. $inactiveDays = max(7, (int)$diffDays - 1);
  669. }
  670. // 总奖励百分比 = 100% 本金 + bonusPercent% 奖励
  671. $totalPercent = 100 + $bonusPercent;
  672. $sevenDaysPercent = $bonusPercent;
  673. // 7 天签到总奖励金额(全部通过签到领取)
  674. $totalBonus = round($payAmt * $bonusPercent / 100, 2);
  675. $now = date('Y-m-d H:i:s');
  676. // 签到从充值次日开始,共 7 天,所以过期时间为创建时间 + 7 天
  677. $expAt = date('Y-m-d H:i:s', strtotime('+7 days'));
  678. DB::connection('write')->table('agent.dbo.inactive_vip_gift_records')->insert([
  679. 'user_id' => $user_id,
  680. 'gift_id' => 305,
  681. 'pay_amount' => $payAmt,
  682. 'total_percent' => $totalPercent,
  683. 'seven_days_percent' => $sevenDaysPercent,
  684. 'per_day_amount' => $totalBonus, // 存储总奖励金额,按比例分配
  685. 'inactive_days' => $inactiveDays,
  686. 'claimed_days_mask' => 0,
  687. 'created_at' => $now,
  688. 'updated_at' => $now,
  689. 'expired_at' => $expAt,
  690. ]);
  691. }
  692. /**
  693. * 创建首充礼包记录
  694. */
  695. public function createFirstPayGiftRecord($user_id, $gift_id, $payAmt)
  696. {
  697. // 检查是否已有记录
  698. $existing = DB::connection('write')->table('agent.dbo.first_pay_gift_records')
  699. ->where('user_id', $user_id)
  700. ->first();
  701. if ($existing) {
  702. \Log::info('首充礼包记录已存在', ['user_id' => $user_id]);
  703. return;
  704. }
  705. // 获取礼包配置
  706. $giftConfig = DB::connection('write')->table('agent.dbo.recharge_gift')
  707. ->where('gift_id', $gift_id)
  708. ->first();
  709. if (!$giftConfig) {
  710. \Log::error('首充礼包配置不存在', ['gift_id' => $gift_id]);
  711. return;
  712. }
  713. // 计算金额
  714. $totalBonusAmount = round($giftConfig->total_bonus * $payAmt / 100, 2);
  715. $bonusInstantlyAmount = round($giftConfig->bonus_instantly * $payAmt / 100, 2);
  716. // 解析JSON数据
  717. $dayRewards = $giftConfig->day_rewards ? json_decode($giftConfig->day_rewards, true) : null;
  718. $bettingBonus = $giftConfig->betting_bonus ? json_decode($giftConfig->betting_bonus, true) : null;
  719. $bettingTask = $giftConfig->betting_task ? json_decode($giftConfig->betting_task, true) : null;
  720. // 计算各部分金额
  721. $dayRewardsTotal = $dayRewards ? round($dayRewards['total_bonus'] * $payAmt / 100, 2) : 0;
  722. $bettingBonusTotal = $bettingBonus ? round($bettingBonus['total_bonus'] * $payAmt / 100, 2) : 0;
  723. $bettingTaskTotal = $bettingTask ? round($bettingTask['total_bonus'] * $payAmt / 100, 2) : 0;
  724. // 创建记录
  725. $data = [
  726. 'user_id' => $user_id,
  727. 'gift_id' => $gift_id,
  728. 'pay_amount' => $payAmt,
  729. 'total_bonus' => $totalBonusAmount,
  730. 'bonus_instantly' => $bonusInstantlyAmount,
  731. 'gift_name' => $giftConfig->gift_name,
  732. // 每日奖励
  733. 'day_rewards_total' => $dayRewardsTotal,
  734. 'day_rewards_claimed' => 0,
  735. 'day_rewards_data' => $giftConfig->day_rewards,
  736. 'day_last_claim_date' => null,
  737. // 下注奖励
  738. 'betting_bonus_total' => $bettingBonusTotal,
  739. 'betting_bonus_claimed' => 0,
  740. 'betting_bonus_data' => $giftConfig->betting_bonus,
  741. 'betting_current_bet' => 0,
  742. // 下注任务
  743. 'betting_task_total' => $bettingTaskTotal,
  744. 'betting_task_claimed' => 0,
  745. 'betting_task_data' => $giftConfig->betting_task,
  746. 'created_at' => date('Y-m-d H:i:s'),
  747. 'updated_at' => date('Y-m-d H:i:s')
  748. ];
  749. DB::connection('write')->table('agent.dbo.first_pay_gift_records')->insert($data);
  750. $dayRewardsTotal = $dayRewards ? round($dayRewards['total_bonus'] * $payAmt / 100, 2) : 0;
  751. $bettingBonusTotal = $bettingBonus ? round($bettingBonus['total_bonus'] * $payAmt / 100, 2) : 0;
  752. $bettingTaskTotal = $bettingTask ? round($bettingTask['total_bonus'] * $payAmt / 100, 2) : 0;
  753. \Log::info('首充礼包记录创建成功', [
  754. 'user_id' => $user_id,
  755. 'gift_id' => $gift_id,
  756. 'pay_amount' => $payAmt,
  757. 'total_bonus' => $totalBonusAmount,
  758. 'rw' => [
  759. $dayRewardsTotal,
  760. $bettingBonusTotal,
  761. $bettingTaskTotal,
  762. round($dayRewards['total_bonus'] * $payAmt / 100, 2),
  763. round($bettingBonus['total_bonus'] * $payAmt / 100, 2),
  764. round($bettingTask['total_bonus'] * $payAmt / 100, 2)
  765. ]
  766. ]);
  767. }
  768. }