UrsRelationCacheLogic.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  1. <?php
  2. namespace App\Module\UrsPromotion\Logics;
  3. use App\Module\UrsPromotion\Enums\UrsPromotionRelationLevel;
  4. use App\Module\UrsPromotion\Models\UrsUserReferral;
  5. use App\Module\UrsPromotion\Models\UrsUserRelationCache;
  6. use App\Module\UrsPromotion\Services\UrsUserMappingService;
  7. use Illuminate\Support\Facades\DB;
  8. use Illuminate\Support\Facades\Log;
  9. use Illuminate\Support\Facades\Redis;
  10. /**
  11. * URS关系缓存逻辑类
  12. *
  13. * 处理URS用户关系缓存的核心业务逻辑,包括生成关系缓存、清理关系缓存、
  14. * 重建关系缓存等功能。该类仅供内部使用,不对外提供服务。
  15. */
  16. class UrsRelationCacheLogic
  17. {
  18. /**
  19. * 生成用户的关系缓存
  20. *
  21. * @param int $ursUserId URS用户ID
  22. * @return bool
  23. */
  24. public function generateUserRelationCache(int $ursUserId): bool
  25. {
  26. try {
  27. // 清除用户的现有关系缓存
  28. $this->clearUserRelationCache($ursUserId);
  29. // 获取用户的直接推荐人
  30. $referral = UrsUserReferral::where('urs_user_id', $ursUserId)
  31. ->where('status', UrsUserReferral::STATUS_VALID)
  32. ->first();
  33. if (!$referral) {
  34. Log::info("URS用户 {$ursUserId} 没有推荐人,无需生成关系缓存");
  35. return true;
  36. }
  37. $ursReferrerId = $referral->urs_referrer_id;
  38. // 获取农场用户ID
  39. $farmUserId = UrsUserMappingService::getFarmUserId($ursUserId);
  40. $farmReferrerId = UrsUserMappingService::getFarmUserId($ursReferrerId);
  41. // 如果当前用户未进入农场,无法生成缓存
  42. if ($farmUserId <= 0) {
  43. Log::info("URS用户 {$ursUserId} 未进入农场,跳过缓存生成");
  44. return true;
  45. }
  46. // 如果推荐人未进入农场,创建占位缓存记录,避免断代问题
  47. if ($farmReferrerId <= 0) {
  48. Log::info("URS用户 {$ursUserId} 的推荐人 {$ursReferrerId} 未进入农场,创建占位缓存记录");
  49. // 检查是否已存在该深度的缓存记录,避免重复插入
  50. $existingCache = UrsUserRelationCache::where('urs_user_id', $ursUserId)
  51. ->where('urs_related_user_id', $ursReferrerId)
  52. ->where('depth', 1)
  53. ->first();
  54. if (!$existingCache) {
  55. // 创建占位的直接关系缓存(农场用户ID为0)
  56. $directRelation = new UrsUserRelationCache();
  57. $directRelation->user_id = $farmUserId;
  58. $directRelation->related_user_id = 0; // 推荐人未进入农场,设为0
  59. $directRelation->urs_user_id = $ursUserId;
  60. $directRelation->urs_related_user_id = $ursReferrerId;
  61. $directRelation->level = UrsPromotionRelationLevel::DIRECT;
  62. $directRelation->path = '0'; // 占位路径
  63. $directRelation->urs_path = (string)$ursReferrerId;
  64. $directRelation->depth = 1;
  65. $directRelation->save();
  66. } else {
  67. Log::debug("URS用户 {$ursUserId} 的占位缓存记录已存在,跳过创建");
  68. }
  69. // 尝试获取推荐人的上级关系(基于URS关系)
  70. $this->generateIndirectRelationsFromUrsChain($ursUserId, $farmUserId, $ursReferrerId, 1);
  71. Log::info("URS用户 {$ursUserId} 占位缓存记录创建完成");
  72. return true;
  73. }
  74. // 创建直接关系缓存
  75. $directRelation = new UrsUserRelationCache();
  76. $directRelation->user_id = $farmUserId;
  77. $directRelation->related_user_id = $farmReferrerId;
  78. $directRelation->urs_user_id = $ursUserId;
  79. $directRelation->urs_related_user_id = $ursReferrerId;
  80. $directRelation->level = UrsPromotionRelationLevel::DIRECT;
  81. $directRelation->path = (string)$farmReferrerId;
  82. $directRelation->urs_path = (string)$ursReferrerId;
  83. $directRelation->depth = 1;
  84. $directRelation->save();
  85. // 获取推荐人的所有上级(限制在20代以内)
  86. $upperRelations = UrsUserRelationCache::where('urs_user_id', $ursReferrerId)
  87. ->where('depth', '<', UrsPromotionRelationLevel::getMaxLevel())
  88. ->get();
  89. // 创建间接关系缓存(最多20代)
  90. foreach ($upperRelations as $upperRelation) {
  91. $newDepth = $upperRelation->depth + 1;
  92. // 限制最大深度为20代
  93. if ($newDepth > UrsPromotionRelationLevel::getMaxLevel()) {
  94. continue;
  95. }
  96. $indirectRelation = new UrsUserRelationCache();
  97. $indirectRelation->user_id = $farmUserId;
  98. $indirectRelation->related_user_id = $upperRelation->related_user_id;
  99. $indirectRelation->urs_user_id = $ursUserId;
  100. $indirectRelation->urs_related_user_id = $upperRelation->urs_related_user_id;
  101. $indirectRelation->level = UrsPromotionRelationLevel::getLevelByDepth($newDepth);
  102. $indirectRelation->path = $farmReferrerId . ',' . $upperRelation->path;
  103. $indirectRelation->urs_path = $ursReferrerId . ',' . $upperRelation->urs_path;
  104. $indirectRelation->depth = $newDepth;
  105. $indirectRelation->save();
  106. }
  107. // 清除Redis缓存
  108. Redis::del("urs_promotion:user:{$ursUserId}:all_referrers");
  109. Redis::del("urs_promotion:farm_user:{$farmUserId}:all_referrers");
  110. Log::info("URS用户 {$ursUserId} 关系缓存生成成功");
  111. return true;
  112. } catch (\Exception $e) {
  113. Log::error("生成URS用户关系缓存失败", [
  114. 'urs_user_id' => $ursUserId,
  115. 'error' => $e->getMessage()
  116. ]);
  117. return false;
  118. }
  119. }
  120. /**
  121. * 基于URS关系链生成间接关系缓存
  122. *
  123. * 当推荐人未进入农场时,通过URS推荐关系链向上查找已进入农场的上级
  124. *
  125. * @param int $ursUserId 当前用户的URS用户ID
  126. * @param int $farmUserId 当前用户的农场用户ID
  127. * @param int $currentUrsReferrerId 当前层级的URS推荐人ID
  128. * @param int $currentDepth 当前深度
  129. * @return void
  130. */
  131. private function generateIndirectRelationsFromUrsChain(int $ursUserId, int $farmUserId, int $currentUrsReferrerId, int $currentDepth): void
  132. {
  133. // 限制最大深度为20代
  134. if ($currentDepth >= UrsPromotionRelationLevel::getMaxLevel()) {
  135. return;
  136. }
  137. // 获取当前推荐人的推荐人
  138. $upperReferral = UrsUserReferral::where('urs_user_id', $currentUrsReferrerId)
  139. ->where('status', UrsUserReferral::STATUS_VALID)
  140. ->first();
  141. if (!$upperReferral) {
  142. // 没有更上级的推荐人,结束递归
  143. return;
  144. }
  145. $upperUrsReferrerId = $upperReferral->urs_referrer_id;
  146. $upperFarmReferrerId = UrsUserMappingService::getFarmUserId($upperUrsReferrerId);
  147. $newDepth = $currentDepth + 1;
  148. if ($upperFarmReferrerId > 0) {
  149. // 检查是否已存在该深度的关系缓存
  150. $existingCache = UrsUserRelationCache::where('urs_user_id', $ursUserId)
  151. ->where('urs_related_user_id', $upperUrsReferrerId)
  152. ->where('depth', $newDepth)
  153. ->first();
  154. if (!$existingCache) {
  155. // 上级推荐人已进入农场,创建有效的关系缓存
  156. $indirectRelation = new UrsUserRelationCache();
  157. $indirectRelation->user_id = $farmUserId;
  158. $indirectRelation->related_user_id = $upperFarmReferrerId;
  159. $indirectRelation->urs_user_id = $ursUserId;
  160. $indirectRelation->urs_related_user_id = $upperUrsReferrerId;
  161. $indirectRelation->level = UrsPromotionRelationLevel::getLevelByDepth($newDepth);
  162. $indirectRelation->path = $this->buildFarmUserPath($currentUrsReferrerId, $upperFarmReferrerId);
  163. $indirectRelation->urs_path = $this->buildUrsPath($currentUrsReferrerId, $upperUrsReferrerId);
  164. $indirectRelation->depth = $newDepth;
  165. $indirectRelation->save();
  166. }
  167. Log::debug("为URS用户 {$ursUserId} 创建间接关系缓存", [
  168. 'upper_urs_referrer_id' => $upperUrsReferrerId,
  169. 'upper_farm_referrer_id' => $upperFarmReferrerId,
  170. 'depth' => $newDepth
  171. ]);
  172. // 继续向上查找,基于已有的关系缓存
  173. $this->generateIndirectRelationsFromExistingCache($ursUserId, $farmUserId, $upperUrsReferrerId, $newDepth);
  174. } else {
  175. // 检查是否已存在该深度的占位缓存
  176. $existingCache = UrsUserRelationCache::where('urs_user_id', $ursUserId)
  177. ->where('urs_related_user_id', $upperUrsReferrerId)
  178. ->where('depth', $newDepth)
  179. ->first();
  180. if (!$existingCache) {
  181. // 上级推荐人也未进入农场,创建占位缓存并继续向上查找
  182. $indirectRelation = new UrsUserRelationCache();
  183. $indirectRelation->user_id = $farmUserId;
  184. $indirectRelation->related_user_id = 0; // 占位
  185. $indirectRelation->urs_user_id = $ursUserId;
  186. $indirectRelation->urs_related_user_id = $upperUrsReferrerId;
  187. $indirectRelation->level = UrsPromotionRelationLevel::getLevelByDepth($newDepth);
  188. $indirectRelation->path = $this->buildFarmUserPath($currentUrsReferrerId, 0);
  189. $indirectRelation->urs_path = $this->buildUrsPath($currentUrsReferrerId, $upperUrsReferrerId);
  190. $indirectRelation->depth = $newDepth;
  191. $indirectRelation->save();
  192. }
  193. // 继续向上递归查找
  194. $this->generateIndirectRelationsFromUrsChain($ursUserId, $farmUserId, $upperUrsReferrerId, $newDepth);
  195. }
  196. }
  197. /**
  198. * 基于已有关系缓存生成间接关系
  199. *
  200. * @param int $ursUserId 当前用户的URS用户ID
  201. * @param int $farmUserId 当前用户的农场用户ID
  202. * @param int $baseUrsReferrerId 基准URS推荐人ID
  203. * @param int $baseDepth 基准深度
  204. * @return void
  205. */
  206. private function generateIndirectRelationsFromExistingCache(int $ursUserId, int $farmUserId, int $baseUrsReferrerId, int $baseDepth): void
  207. {
  208. // 获取基准推荐人的所有上级关系缓存
  209. $upperRelations = UrsUserRelationCache::where('urs_user_id', $baseUrsReferrerId)
  210. ->where('depth', '<', UrsPromotionRelationLevel::getMaxLevel() - $baseDepth)
  211. ->get();
  212. foreach ($upperRelations as $upperRelation) {
  213. $newDepth = $baseDepth + $upperRelation->depth;
  214. // 限制最大深度为20代
  215. if ($newDepth > UrsPromotionRelationLevel::getMaxLevel()) {
  216. continue;
  217. }
  218. // 检查是否已存在该深度的关系缓存
  219. $existingCache = UrsUserRelationCache::where('urs_user_id', $ursUserId)
  220. ->where('urs_related_user_id', $upperRelation->urs_related_user_id)
  221. ->where('depth', $newDepth)
  222. ->first();
  223. if (!$existingCache) {
  224. $indirectRelation = new UrsUserRelationCache();
  225. $indirectRelation->user_id = $farmUserId;
  226. $indirectRelation->related_user_id = $upperRelation->related_user_id;
  227. $indirectRelation->urs_user_id = $ursUserId;
  228. $indirectRelation->urs_related_user_id = $upperRelation->urs_related_user_id;
  229. $indirectRelation->level = UrsPromotionRelationLevel::getLevelByDepth($newDepth);
  230. $indirectRelation->path = $this->buildCombinedFarmPath($baseUrsReferrerId, $upperRelation->path);
  231. $indirectRelation->urs_path = $this->buildCombinedUrsPath($baseUrsReferrerId, $upperRelation->urs_path);
  232. $indirectRelation->depth = $newDepth;
  233. $indirectRelation->save();
  234. }
  235. }
  236. }
  237. /**
  238. * 构建农场用户路径
  239. */
  240. private function buildFarmUserPath(int $currentUrsReferrerId, int $upperFarmReferrerId): string
  241. {
  242. $currentFarmReferrerId = UrsUserMappingService::getFarmUserId($currentUrsReferrerId);
  243. $currentPart = $currentFarmReferrerId > 0 ? (string)$currentFarmReferrerId : '0';
  244. if ($upperFarmReferrerId > 0) {
  245. return $currentPart . ',' . $upperFarmReferrerId;
  246. }
  247. return $currentPart;
  248. }
  249. /**
  250. * 构建URS用户路径
  251. */
  252. private function buildUrsPath(int $currentUrsReferrerId, int $upperUrsReferrerId): string
  253. {
  254. return $currentUrsReferrerId . ',' . $upperUrsReferrerId;
  255. }
  256. /**
  257. * 构建组合农场用户路径
  258. */
  259. private function buildCombinedFarmPath(int $baseUrsReferrerId, string $upperPath): string
  260. {
  261. $baseFarmReferrerId = UrsUserMappingService::getFarmUserId($baseUrsReferrerId);
  262. $basePart = $baseFarmReferrerId > 0 ? (string)$baseFarmReferrerId : '0';
  263. return $basePart . ',' . $upperPath;
  264. }
  265. /**
  266. * 构建组合URS用户路径
  267. */
  268. private function buildCombinedUrsPath(int $baseUrsReferrerId, string $upperUrsPath): string
  269. {
  270. return $baseUrsReferrerId . ',' . $upperUrsPath;
  271. }
  272. /**
  273. * 清除用户的关系缓存
  274. *
  275. * @param int $ursUserId URS用户ID
  276. * @return bool
  277. */
  278. public function clearUserRelationCache(int $ursUserId): bool
  279. {
  280. try {
  281. // 获取农场用户ID
  282. $farmUserId = UrsUserMappingService::getFarmUserId($ursUserId);
  283. // 删除数据库中的关系缓存
  284. UrsUserRelationCache::where('urs_user_id', $ursUserId)->delete();
  285. // 清除Redis缓存
  286. Redis::del("urs_promotion:user:{$ursUserId}:all_referrers");
  287. if ($farmUserId > 0) {
  288. Redis::del("urs_promotion:farm_user:{$farmUserId}:all_referrers");
  289. }
  290. return true;
  291. } catch (\Exception $e) {
  292. Log::error("清除URS用户关系缓存失败", [
  293. 'urs_user_id' => $ursUserId,
  294. 'error' => $e->getMessage()
  295. ]);
  296. return false;
  297. }
  298. }
  299. /**
  300. * 重建所有用户的关系缓存
  301. *
  302. * @param int $batchSize 批处理大小
  303. * @return array 包含成功和失败的数量
  304. */
  305. public function rebuildAllRelationCache(int $batchSize = 100): array
  306. {
  307. try {
  308. // 清空关系缓存表
  309. UrsUserRelationCache::truncate();
  310. // 清除所有Redis缓存
  311. $keys = Redis::keys("urs_promotion:user:*:all_referrers");
  312. if (!empty($keys)) {
  313. Redis::del($keys);
  314. }
  315. $keys = Redis::keys("urs_promotion:farm_user:*:all_referrers");
  316. if (!empty($keys)) {
  317. Redis::del($keys);
  318. }
  319. // 获取所有URS用户ID
  320. $ursUserIds = UrsUserReferral::where('status', UrsUserReferral::STATUS_VALID)
  321. ->pluck('urs_user_id')
  322. ->toArray();
  323. $successCount = 0;
  324. $failCount = 0;
  325. // 分批处理
  326. $chunks = array_chunk($ursUserIds, $batchSize);
  327. foreach ($chunks as $chunk) {
  328. foreach ($chunk as $ursUserId) {
  329. if ($this->generateUserRelationCache($ursUserId)) {
  330. $successCount++;
  331. } else {
  332. $failCount++;
  333. }
  334. }
  335. }
  336. Log::info("URS关系缓存重建完成", [
  337. 'success' => $successCount,
  338. 'fail' => $failCount,
  339. 'total' => count($ursUserIds)
  340. ]);
  341. return [
  342. 'success' => $successCount,
  343. 'fail' => $failCount,
  344. 'total' => count($ursUserIds)
  345. ];
  346. } catch (\Exception $e) {
  347. Log::error("重建所有URS关系缓存失败: " . $e->getMessage());
  348. return [
  349. 'success' => 0,
  350. 'fail' => 0,
  351. 'total' => 0,
  352. 'error' => $e->getMessage()
  353. ];
  354. }
  355. }
  356. /**
  357. * 检查关系缓存的完整性
  358. *
  359. * @return array 包含检查结果
  360. */
  361. public function checkRelationCacheIntegrity(): array
  362. {
  363. try {
  364. $totalUsers = UrsUserReferral::where('status', UrsUserReferral::STATUS_VALID)->count();
  365. $usersWithCache = UrsUserRelationCache::distinct('urs_user_id')->count('urs_user_id');
  366. $missingUsers = $totalUsers - $usersWithCache;
  367. // 检查循环推荐关系
  368. $circularRelations = DB::select("
  369. SELECT r1.urs_user_id, r1.urs_referrer_id
  370. FROM kku_urs_promotion_user_referrals r1
  371. JOIN kku_urs_promotion_user_referrals r2 ON r1.urs_referrer_id = r2.urs_user_id
  372. WHERE r2.urs_referrer_id = r1.urs_user_id
  373. AND r1.status = 1 AND r2.status = 1
  374. ");
  375. // 检查孤立的缓存
  376. $orphanedCaches = DB::select("
  377. SELECT c.urs_user_id
  378. FROM kku_urs_promotion_user_relation_cache c
  379. LEFT JOIN kku_urs_promotion_user_referrals r ON c.urs_user_id = r.urs_user_id AND r.status = 1
  380. WHERE r.urs_user_id IS NULL
  381. ");
  382. return [
  383. 'total_users' => $totalUsers,
  384. 'users_with_cache' => $usersWithCache,
  385. 'missing_users' => $missingUsers,
  386. 'circular_relations' => count($circularRelations),
  387. 'orphaned_caches' => count($orphanedCaches)
  388. ];
  389. } catch (\Exception $e) {
  390. Log::error("检查URS关系缓存完整性失败: " . $e->getMessage());
  391. return [
  392. 'error' => $e->getMessage()
  393. ];
  394. }
  395. }
  396. /**
  397. * 修复关系缓存问题
  398. *
  399. * @return array 包含修复结果
  400. */
  401. public function fixRelationCacheIssues(): array
  402. {
  403. try {
  404. // 检查完整性
  405. $integrity = $this->checkRelationCacheIntegrity();
  406. $fixed = [
  407. 'missing_users' => 0,
  408. 'orphaned_caches' => 0
  409. ];
  410. // 修复缺失的用户缓存
  411. if ($integrity['missing_users'] > 0) {
  412. $usersWithCache = UrsUserRelationCache::distinct('urs_user_id')->pluck('urs_user_id')->toArray();
  413. $allUsers = UrsUserReferral::where('status', UrsUserReferral::STATUS_VALID)
  414. ->pluck('urs_user_id')
  415. ->toArray();
  416. $missingUsers = array_diff($allUsers, $usersWithCache);
  417. foreach ($missingUsers as $ursUserId) {
  418. if ($this->generateUserRelationCache($ursUserId)) {
  419. $fixed['missing_users']++;
  420. }
  421. }
  422. }
  423. // 清理孤立的缓存
  424. if ($integrity['orphaned_caches'] > 0) {
  425. $orphanedCaches = DB::select("
  426. SELECT c.urs_user_id
  427. FROM kku_urs_promotion_user_relation_cache c
  428. LEFT JOIN kku_urs_promotion_user_referrals r ON c.urs_user_id = r.urs_user_id AND r.status = 1
  429. WHERE r.urs_user_id IS NULL
  430. ");
  431. foreach ($orphanedCaches as $cache) {
  432. if ($this->clearUserRelationCache($cache->urs_user_id)) {
  433. $fixed['orphaned_caches']++;
  434. }
  435. }
  436. }
  437. return [
  438. 'integrity' => $integrity,
  439. 'fixed' => $fixed
  440. ];
  441. } catch (\Exception $e) {
  442. Log::error("修复URS关系缓存问题失败: " . $e->getMessage());
  443. return [
  444. 'error' => $e->getMessage()
  445. ];
  446. }
  447. }
  448. /**
  449. * 为特定用户更新农场用户ID相关的缓存
  450. *
  451. * @param int $ursUserId URS用户ID
  452. * @param int $farmUserId 农场用户ID
  453. * @return bool
  454. */
  455. public function updateFarmUserIdInCache(int $ursUserId, int $farmUserId): bool
  456. {
  457. try {
  458. // 更新该用户作为被推荐人的缓存记录
  459. UrsUserRelationCache::where('urs_user_id', $ursUserId)
  460. ->update(['user_id' => $farmUserId]);
  461. // 更新该用户作为推荐人的缓存记录(将占位的0更新为实际农场用户ID)
  462. $updatedCount = UrsUserRelationCache::where('urs_related_user_id', $ursUserId)
  463. ->where('related_user_id', 0) // 只更新占位记录
  464. ->update(['related_user_id' => $farmUserId]);
  465. if ($updatedCount > 0) {
  466. Log::info("更新了 {$updatedCount} 条占位缓存记录", [
  467. 'urs_user_id' => $ursUserId,
  468. 'farm_user_id' => $farmUserId
  469. ]);
  470. // 更新路径中的占位符
  471. $this->updatePlaceholderPaths($ursUserId, $farmUserId);
  472. }
  473. // 重新生成该用户的关系缓存(确保路径正确)
  474. $this->generateUserRelationCache($ursUserId);
  475. // 为该用户的所有下级重新生成缓存(修复断代问题)
  476. $this->regenerateDownstreamCaches($ursUserId);
  477. Log::info("URS用户关系缓存中的农场用户ID更新成功", [
  478. 'urs_user_id' => $ursUserId,
  479. 'farm_user_id' => $farmUserId,
  480. 'updated_placeholder_count' => $updatedCount
  481. ]);
  482. return true;
  483. } catch (\Exception $e) {
  484. Log::error("更新URS用户关系缓存中的农场用户ID失败", [
  485. 'urs_user_id' => $ursUserId,
  486. 'farm_user_id' => $farmUserId,
  487. 'error' => $e->getMessage()
  488. ]);
  489. return false;
  490. }
  491. }
  492. /**
  493. * 更新路径中的占位符
  494. *
  495. * @param int $ursUserId URS用户ID
  496. * @param int $farmUserId 农场用户ID
  497. * @return void
  498. */
  499. private function updatePlaceholderPaths(int $ursUserId, int $farmUserId): void
  500. {
  501. try {
  502. // 获取所有包含该用户的路径记录
  503. $records = UrsUserRelationCache::where('urs_path', 'LIKE', "%{$ursUserId}%")->get();
  504. foreach ($records as $record) {
  505. $pathParts = explode(',', $record->path);
  506. $ursPathParts = explode(',', $record->urs_path);
  507. // 找到URS路径中对应的位置,更新农场用户路径
  508. $ursIndex = array_search((string)$ursUserId, $ursPathParts);
  509. if ($ursIndex !== false && isset($pathParts[$ursIndex]) && $pathParts[$ursIndex] === '0') {
  510. $pathParts[$ursIndex] = (string)$farmUserId;
  511. $record->path = implode(',', $pathParts);
  512. $record->save();
  513. }
  514. }
  515. Log::debug("更新路径占位符完成", [
  516. 'urs_user_id' => $ursUserId,
  517. 'farm_user_id' => $farmUserId,
  518. 'updated_records' => $records->count()
  519. ]);
  520. } catch (\Exception $e) {
  521. Log::warning("更新路径占位符失败", [
  522. 'urs_user_id' => $ursUserId,
  523. 'farm_user_id' => $farmUserId,
  524. 'error' => $e->getMessage()
  525. ]);
  526. }
  527. }
  528. /**
  529. * 为用户的所有下级重新生成缓存
  530. *
  531. * 当用户进入农场后,需要为其所有下级重新生成缓存以修复断代问题
  532. *
  533. * @param int $ursUserId URS用户ID
  534. * @return void
  535. */
  536. private function regenerateDownstreamCaches(int $ursUserId): void
  537. {
  538. try {
  539. // 获取该用户的所有直接下级
  540. $directSubordinates = UrsUserReferral::where('urs_referrer_id', $ursUserId)
  541. ->where('status', UrsUserReferral::STATUS_VALID)
  542. ->pluck('urs_user_id')
  543. ->toArray();
  544. if (empty($directSubordinates)) {
  545. return;
  546. }
  547. Log::info("开始为用户的下级重新生成缓存", [
  548. 'urs_user_id' => $ursUserId,
  549. 'subordinate_count' => count($directSubordinates)
  550. ]);
  551. foreach ($directSubordinates as $subordinateUrsUserId) {
  552. // 检查下级是否已进入农场
  553. $subordinateFarmUserId = UrsUserMappingService::getFarmUserId($subordinateUrsUserId);
  554. if ($subordinateFarmUserId > 0) {
  555. // 重新生成下级的关系缓存
  556. $this->generateUserRelationCache($subordinateUrsUserId);
  557. // 递归处理下级的下级
  558. $this->regenerateDownstreamCaches($subordinateUrsUserId);
  559. }
  560. }
  561. Log::info("用户下级缓存重新生成完成", [
  562. 'urs_user_id' => $ursUserId
  563. ]);
  564. } catch (\Exception $e) {
  565. Log::error("重新生成下级缓存失败", [
  566. 'urs_user_id' => $ursUserId,
  567. 'error' => $e->getMessage()
  568. ]);
  569. }
  570. }
  571. }