AgentClickController.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use App\Facade\TableName;
  4. use App\Http\Controllers\Controller;
  5. use App\IpLocation;
  6. use App\Models\AccountsInfo;
  7. use App\Models\AgentClickLog;
  8. use App\Models\AgentUserInfo;
  9. use App\Models\AgentUserRecord;
  10. use App\Services\IpCheck;
  11. use Illuminate\Http\Request;
  12. use Illuminate\Support\Facades\DB;
  13. use Illuminate\Support\Facades\Log;
  14. class AgentClickController extends Controller
  15. {
  16. /**
  17. * 记录链接点击信息
  18. */
  19. public function recordClickPage(Request $request)
  20. {
  21. // 获取邀请码
  22. $code = $request->query('code');
  23. if (empty($code)||strlen($code)>6) {
  24. return response()->json([
  25. 'success' => false,
  26. 'message' => 'Invitation code is required'
  27. ], 400);
  28. }
  29. $ip=IpLocation::getIP();
  30. $agent=$_SERVER['HTTP_USER_AGENT'];
  31. if(AgentClickLog::query()->where('client_ip',$ip)->where('user_agent',$agent)->exists()){
  32. }else{
  33. // 检查邀请码是否存在
  34. $agentInfo = AgentUserInfo::where('referral_code', $code)->first();
  35. if (!$agentInfo) {
  36. // 仍然记录点击,但标记为无效
  37. $isValid = false;
  38. } else {
  39. $isValid = true;
  40. }
  41. $res=IpCheck::getGeoLocation($ip);
  42. // 检测设备类型
  43. $deviceType = AgentClickLog::detectDeviceType($agent);
  44. $referrer = $_SERVER['HTTP_ORIGIN'] ??$_SERVER['HTTP_REFERER']?? '';
  45. // 记录点击信息
  46. $clickLog = new AgentClickLog();
  47. $clickLog->code = $code;
  48. $clickLog->country = $res['country'];
  49. $clickLog->city = $res['city'];
  50. $clickLog->user_agent = $agent;
  51. $clickLog->client_ip = $ip;
  52. $clickLog->referrer = $referrer;
  53. $clickLog->device_type = $deviceType;
  54. $clickLog->is_valid = $isValid ? 1 : 0;
  55. $clickLog->save();
  56. }
  57. return "OK";
  58. }
  59. /**
  60. * 记录链接点击信息
  61. */
  62. public function recordClick(Request $request)
  63. {
  64. // 获取邀请码
  65. $code = $request->query('code');
  66. if (empty($code)||strlen($code)>6) {
  67. return response()->json([
  68. 'success' => false,
  69. 'message' => 'Invitation code is required'
  70. ], 400);
  71. }
  72. // 检查邀请码是否存在
  73. $agentInfo = AgentUserInfo::where('referral_code', $code)->first();
  74. if (!$agentInfo) {
  75. // 仍然记录点击,但标记为无效
  76. $isValid = false;
  77. } else {
  78. $isValid = true;
  79. }
  80. // 解析add参数中的JSON数据
  81. $addParam = $request->query('add');
  82. $clickData = [];
  83. if (!empty($addParam)) {
  84. try {
  85. $clickData = json_decode(urldecode($addParam), true) ?: [];
  86. } catch (\Exception $e) {
  87. Log::error('Error decoding click data: ' . $e->getMessage());
  88. $clickData = [];
  89. }
  90. }
  91. // 获取客户端信息
  92. $userAgent = $clickData['userAgent'] ?? $request->header('User-Agent');
  93. $country = $clickData['country'] ?? null;
  94. $city = $clickData['city'] ?? null;
  95. $clientIp = $clickData['clientIp'] ?? $request->ip();
  96. $referrer = $request->header('referer');
  97. // 检测设备类型
  98. $deviceType = AgentClickLog::detectDeviceType($userAgent);
  99. // 记录点击信息
  100. $clickLog = new AgentClickLog();
  101. $clickLog->code = $code;
  102. $clickLog->country = $country;
  103. $clickLog->city = $city;
  104. $clickLog->user_agent = $userAgent;
  105. $clickLog->client_ip = $clientIp;
  106. $clickLog->referrer = $referrer;
  107. $clickLog->device_type = $deviceType;
  108. $clickLog->is_valid = $isValid ? 1 : 0;
  109. $clickLog->save();
  110. // 如果需要重定向到某个页面
  111. if ($request->has('redirect')) {
  112. return redirect($request->query('redirect'));
  113. }
  114. // 返回1x1透明GIF图像
  115. $gif = base64_decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7');
  116. return response($gif, 200)
  117. ->header('Content-Type', 'image/gif')
  118. ->header('Content-Length', strlen($gif));
  119. }
  120. /**
  121. * 用户归属渠道变更时,同步分渠道日统计(RecordPlatformData),并尽力同步 LogOnLineCountSum(若表含 Channel 列)。
  122. *
  123. * @param int|string $orgChannel 原渠道
  124. * @param int|string $newChannel 新渠道
  125. * @param string|null $dateId 统计日期 Ymd(应用注册日);null 则当前服务器日,兼容旧调用
  126. */
  127. static function changePlatformData($orgChannel, $newChannel, $dateId = null)
  128. {
  129. $org = (int) $orgChannel;
  130. $nw = (int) $newChannel;
  131. if ($org === $nw) {
  132. return false;
  133. }
  134. $dateId = $dateId ?: date('Ymd');
  135. DB::connection('write')->table(TableName::QPRecordDB() . 'RecordPlatformData')
  136. ->where('DateID', $dateId)
  137. ->where('Channel', $org)
  138. ->update(['RegPeple' => DB::raw('RegPeple-1')]);
  139. DB::connection('write')->table(TableName::QPRecordDB() . 'RecordPlatformData')
  140. ->where('DateID', $dateId)
  141. ->where('Channel', $nw)
  142. ->update(['RegPeple' => DB::raw('RegPeple+1')]);
  143. //self::syncLogOnLineCountSumRegisterByChannel($org, $nw, $dateId);
  144. return true;
  145. }
  146. /**
  147. * 若 QPRecordDB.dbo.LogOnLineCountSum 存在 Channel、RegisterCount 且按日聚合,则在渠道迁移时调整分渠道新增注册数。
  148. * 若库表无 Channel 列或结构与假设不符,静默跳过(记录 debug 日志)。
  149. */
  150. private static function syncLogOnLineCountSumRegisterByChannel(int $orgChannel, int $newChannel, string $dateId): void
  151. {
  152. if (!preg_match('/^\d{8}$/', $dateId)) {
  153. return;
  154. }
  155. $dateStr = substr($dateId, 0, 4) . '-' . substr($dateId, 4, 2) . '-' . substr($dateId, 6, 2);
  156. try {
  157. $tbl = TableName::QPRecordDB() . 'LogOnLineCountSum';
  158. DB::connection('write')->update(
  159. 'UPDATE ' . $tbl . ' SET RegisterCount = CASE WHEN RegisterCount > 0 THEN RegisterCount - 1 ELSE 0 END '
  160. . 'WHERE CAST(InsertDateTime AS DATE) = CAST(? AS DATE) AND Channel = ?',
  161. [$dateStr, $orgChannel]
  162. );
  163. DB::connection('write')->update(
  164. 'UPDATE ' . $tbl . ' SET RegisterCount = RegisterCount + 1 '
  165. . 'WHERE CAST(InsertDateTime AS DATE) = CAST(? AS DATE) AND Channel = ?',
  166. [$dateStr, $newChannel]
  167. );
  168. } catch (\Throwable $e) {
  169. Log::debug('LogOnLineCountSum RegisterCount sync skipped (schema mismatch or no Channel)', [
  170. 'message' => $e->getMessage(),
  171. 'org' => $orgChannel,
  172. 'new' => $newChannel,
  173. 'dateId' => $dateId,
  174. ]);
  175. }
  176. }
  177. public static function checkClick($UserID)
  178. {
  179. // if(AccountsInfo::where('UserID', $UserID)->value('SpreaderID')!=0){
  180. // return;
  181. // }
  182. $SpreaderID=AgentUserRecord::where('UserID', $UserID)->value('SpreaderID');
  183. $UserSpreaderID=AccountsInfo::where('UserID', $UserID)->value('SpreaderID');
  184. if(intval($UserSpreaderID)){
  185. return;
  186. }
  187. if(intval($SpreaderID)){
  188. if($UserID!=$SpreaderID){
  189. $userAcc = AccountsInfo::find($UserID);
  190. if (!$userAcc) {
  191. return;
  192. }
  193. $orgChannel = $userAcc->Channel;
  194. $newChannel = AccountsInfo::find($SpreaderID)->Channel;
  195. $registerDateId = $userAcc->RegisterDate ? date('Ymd', strtotime($userAcc->RegisterDate)) : date('Ymd');
  196. $BlockInviteChannel=DB::table('QPPlatformDB.dbo.ChannelPackageName')->where('Channel',$newChannel)->value('BlockInviteChannel');
  197. if($BlockInviteChannel==1){
  198. AccountsInfo::where('UserID', $UserID)->update(['SpreaderID' => $SpreaderID]);
  199. }else {
  200. AccountsInfo::where('UserID', $UserID)->update(['SpreaderID' => $SpreaderID, 'Channel' => $newChannel]);
  201. self::changePlatformData($orgChannel, $newChannel, $registerDateId);
  202. }
  203. }
  204. return;
  205. }
  206. $ip=IpLocation::getIP();
  207. $agent=$_SERVER['HTTP_USER_AGENT'];
  208. $clicks = AgentClickLog::where('client_ip', $ip)->where('is_valid', 1)->orderByDesc('id')->get();
  209. if($clicks) {
  210. $validClick = null;
  211. foreach ($clicks as $click) {
  212. if ($click->user_agent == $agent) {
  213. $validClick = $click;
  214. break;
  215. }
  216. }
  217. if (!$validClick) {
  218. foreach ($clicks as $click) {
  219. $validClick =$click;
  220. break;
  221. }
  222. }
  223. if($validClick) {
  224. $agentInfo=(new AgentController())->processReferral($UserID,$validClick->code);
  225. if($agentInfo) {
  226. //不能是自己
  227. if($agentInfo->UserID==$UserID)return;
  228. $click->is_valid = 2;
  229. $click->save();
  230. $userAcc = AccountsInfo::find($UserID);
  231. if (!$userAcc) {
  232. return;
  233. }
  234. $orgChannel = $userAcc->Channel;
  235. $newChannel = AccountsInfo::find($agentInfo->UserID)->Channel;
  236. $registerDateId = $userAcc->RegisterDate ? date('Ymd', strtotime($userAcc->RegisterDate)) : date('Ymd');
  237. $BlockInviteChannel=DB::table('QPPlatformDB.dbo.ChannelPackageName')->where('Channel',$newChannel)->value('BlockInviteChannel');
  238. if($BlockInviteChannel==1){
  239. AccountsInfo::where('UserID', $UserID)->update(['SpreaderID' => $agentInfo->UserID]);
  240. }else {
  241. AccountsInfo::where('UserID', $UserID)->update(['SpreaderID'=>$agentInfo->UserID,'Channel'=>$newChannel]);
  242. self::changePlatformData($orgChannel, $newChannel, $registerDateId);
  243. }
  244. }
  245. }
  246. }
  247. }
  248. /**
  249. * 获取点击统计数据(可添加权限控制)
  250. */
  251. public function getClickStats(Request $request)
  252. {
  253. $userId = $request->UserID;
  254. // 获取用户的邀请码
  255. $agentInfo = AgentUserInfo::where('UserID', $userId)->first();
  256. if (!$agentInfo) {
  257. return apiReturnFail('Agent information not found');
  258. }
  259. $code = $agentInfo->referral_code;
  260. // 统计总点击数
  261. $totalClicks = AgentClickLog::where('code', $code)->count();
  262. // 按设备类型统计
  263. $deviceStats = AgentClickLog::where('code', $code)
  264. ->selectRaw('device_type, COUNT(*) as count')
  265. ->groupBy('device_type')
  266. ->get()
  267. ->pluck('count', 'device_type')
  268. ->toArray();
  269. // 按国家统计
  270. $countryStats = AgentClickLog::where('code', $code)
  271. ->whereNotNull('country')
  272. ->selectRaw('country, COUNT(*) as count')
  273. ->groupBy('country')
  274. ->orderByDesc('count')
  275. ->limit(10)
  276. ->get()
  277. ->toArray();
  278. // 按日期统计
  279. $dailyStats = AgentClickLog::where('code', $code)
  280. ->selectRaw('DATE(created_at) as date, COUNT(*) as count')
  281. ->groupBy('date')
  282. ->orderByDesc('date')
  283. ->limit(15)
  284. ->get()
  285. ->toArray();
  286. return apiReturnSuc([
  287. 'total_clicks' => $totalClicks,
  288. 'device_stats' => $deviceStats,
  289. 'country_stats' => $countryStats,
  290. 'daily_stats' => $dailyStats
  291. ]);
  292. }
  293. }