SharedProsperityUserRepository.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824
  1. <?php
  2. namespace app\common\repositories\shared;
  3. use app\common\dao\shared\SharedProsperityUserDao;
  4. use app\common\dao\user\UserDao;
  5. use app\common\enum\CommonEnum;
  6. use app\common\enum\shared\SharedProsperityRewardRecordEnum;
  7. use app\common\enum\shared\SharedProsperityUserEnum;
  8. use app\common\repositories\BaseRepository;
  9. use app\common\repositories\store\order\StoreOrderRepository;
  10. use app\entity\data\shared\SharedProsperityRecommendConfigEntity;
  11. use app\entity\data\shared\SharedProsperityUserEntity;
  12. use think\db\exception\DbException;
  13. class SharedProsperityUserRepository extends BaseRepository
  14. {
  15. protected $dao;
  16. /**
  17. * SharedProsperityUserRepository constructor.
  18. * @param SharedProsperityUserDao $dao
  19. */
  20. public function __construct(SharedProsperityUserDao $dao)
  21. {
  22. $this->dao = $dao;
  23. }
  24. /**
  25. * @param int $id
  26. * @return SharedProsperityUserEntity
  27. */
  28. public function getSharedProsperityUserEntityById(int $id): SharedProsperityUserEntity
  29. {
  30. $entityList = $this->getSharedProsperityUserEntityListByIdList([$id]);
  31. $entity = array_shift($entityList);
  32. if ($entity instanceof SharedProsperityUserEntity) {
  33. return $entity;
  34. } else {
  35. /** @var SharedProsperityUserEntity */
  36. return SharedProsperityUserEntity::newInstance();
  37. }
  38. }
  39. /**
  40. * @param array $idList
  41. * @return SharedProsperityUserEntity[]
  42. */
  43. public function getSharedProsperityUserEntityListByIdList(array $idList): array
  44. {
  45. return $this->dao->getSharedProsperityUserEntityListByIdList($idList);
  46. }
  47. /**
  48. * @param int $userId
  49. * @return SharedProsperityUserEntity
  50. */
  51. public function getSharedProsperityUserEntityByUserId(int $userId): SharedProsperityUserEntity
  52. {
  53. $entityList = $this->getSharedProsperityUserEntityListByUserIdList([$userId]);
  54. $entity = array_shift($entityList);
  55. if ($entity instanceof SharedProsperityUserEntity) {
  56. return $entity;
  57. } else {
  58. /** @var SharedProsperityUserEntity */
  59. return SharedProsperityUserEntity::newInstance();
  60. }
  61. }
  62. /**
  63. * @param array $userIdList
  64. * @return SharedProsperityUserEntity[]
  65. */
  66. public function getSharedProsperityUserEntityListByUserIdList(array $userIdList): array
  67. {
  68. return $this->dao->getSharedProsperityUserEntityListByUserIdList($userIdList);
  69. }
  70. /**
  71. * 获取直接下级用户ID列表
  72. * @param int $parentId 用户ID
  73. * @return SharedProsperityUserEntity[] 直接下级用户ID列表
  74. */
  75. public function getSharedProsperityUserEntityListByParentId(int $parentId): array
  76. {
  77. return $this->dao->getSharedProsperityUserEntityListByParentId($parentId);
  78. }
  79. /**
  80. * @param array $userIdList
  81. * @return SharedProsperityUserEntity[]
  82. */
  83. public function getSharedProsperityUserEntityMapByUserIdList(array $userIdList): array
  84. {
  85. $sharedProsperityUserEntityList = $this->dao->getSharedProsperityUserEntityListByUserIdList($userIdList);
  86. /** @var SharedProsperityUserEntity[] $sharedProsperityUserEntityMapByUserId */
  87. $sharedProsperityUserEntityMapByUserId = array_column($sharedProsperityUserEntityList, null, 'userId');
  88. return $sharedProsperityUserEntityMapByUserId;
  89. }
  90. public function create($data)
  91. {
  92. return $this->dao->create($data);
  93. }
  94. /**
  95. * @param SharedProsperityUserEntity $sharedProsperityUserEntity
  96. * @return SharedProsperityUserEntity
  97. */
  98. public function createByEntity(SharedProsperityUserEntity $sharedProsperityUserEntity): SharedProsperityUserEntity
  99. {
  100. $result = $this->create($sharedProsperityUserEntity->toUnderlineArray())->toArray();
  101. /** @var SharedProsperityUserEntity $entity */
  102. $entity = SharedProsperityUserEntity::newInstance($result);
  103. return $entity;
  104. }
  105. /**
  106. * @param $id
  107. * @param $data
  108. * @return int
  109. */
  110. public function update($id, $data): int
  111. {
  112. try {
  113. return $this->dao->update($id, $data);
  114. } catch (DbException $e) {
  115. return 0;
  116. }
  117. }
  118. public function updateByUserId($userId, $data): int
  119. {
  120. try {
  121. return $this->dao->updateByUserId($userId, $data);
  122. } catch (DbException $e) {
  123. return 0;
  124. }
  125. }
  126. /**
  127. * @param SharedProsperityUserEntity $sharedProsperityUserEntity
  128. * @return SharedProsperityUserEntity
  129. */
  130. public function updateByEntity(SharedProsperityUserEntity $sharedProsperityUserEntity): SharedProsperityUserEntity
  131. {
  132. if (empty($sharedProsperityUserEntity->getId())) {
  133. return SharedProsperityUserEntity::newInstance();
  134. }
  135. $result = $this->update($sharedProsperityUserEntity->getId(), $sharedProsperityUserEntity->toUnderlineArray());
  136. if ($result > 0) {
  137. return $this->getSharedProsperityUserEntityById($sharedProsperityUserEntity->getId());
  138. }
  139. return SharedProsperityUserEntity::newInstance();
  140. }
  141. /**
  142. * 绑定 上级
  143. * @param int $userId
  144. * @param int $parentId
  145. * @return bool
  146. */
  147. public function bindParentId(int $userId, int $parentId): bool
  148. {
  149. $sharedProsperityUserEntity = $this->getSharedProsperityUserEntityByUserId($userId);
  150. if (empty($sharedProsperityUserEntity->getUserId())) {
  151. return false;
  152. }
  153. $sharedProsperityUserEntityByParentId = $this->getSharedProsperityUserEntityByUserId($parentId);
  154. if (empty($sharedProsperityUserEntityByParentId->getUserId())) {
  155. return false;
  156. }
  157. $sharedProsperityUserEntity = $this->updateByEntity($sharedProsperityUserEntity->setParentId($sharedProsperityUserEntityByParentId->getUserId()));
  158. if (empty($sharedProsperityUserEntity->getId())) {
  159. return false;
  160. }
  161. return true;
  162. }
  163. /**
  164. * 获取直推用户列表,并计算每个直推用户的团队总人数和团队总业绩(包含自己)
  165. * 返回三个列表:全部直推、大部门(团队业绩最大的直推用户)、小部门(其余直推用户)
  166. * 同时返回统计数据:我的部门总人数、总业绩、小部门业绩总和、大部门业绩总和
  167. * @param int $userId
  168. * @return array
  169. */
  170. public function getTeam(int $userId): array
  171. {
  172. // 获取直推用户
  173. $list = $this->dao->getDirectByUserId($userId);
  174. if (empty($list)) {
  175. // 没有直推用户,仍然返回统计数据(我的部门总人数和总业绩)
  176. $myTeamUserIds = $this->dao->getAllSubordinateUserIds($userId);
  177. $myTeamTotalCount = count($myTeamUserIds);
  178. $myTeamPvSum = $this->dao->getTeamPvSumWithSelf($userId);
  179. return [
  180. 'all_direct' => [],
  181. 'big_department' => [],
  182. 'small_department' => [],
  183. 'stats' => [
  184. 'my_team_total_count' => $myTeamTotalCount,
  185. 'my_team_pv_sum' => $myTeamPvSum,
  186. 'small_department_pv_sum' => 0,
  187. 'big_department_pv_sum' => 0,
  188. ]
  189. ];
  190. }
  191. // 收集所有直推用户ID
  192. $userIds = array_column($list, 'user_id');
  193. // 获取用户详细信息(昵称、头像、注册时间)
  194. /** @var UserDao $userDao */
  195. $userDao = app()->make(UserDao::class);
  196. $userEntities = $userDao->getUserEntityListByUidList($userIds);
  197. $userMap = [];
  198. foreach ($userEntities as $userEntity) {
  199. $userMap[$userEntity->getUid()] = [
  200. 'nickname' => $userEntity->getNickname(),
  201. 'avatar' => $userEntity->getAvatar(),
  202. 'create_time' => $userEntity->getCreateTime(),
  203. ];
  204. }
  205. // 计算每个直推用户的团队总人数和团队总业绩
  206. $maxPv = 0;
  207. $maxPvIndex = -1;
  208. foreach ($list as $index => &$item) {
  209. $teamUserIds = $this->dao->getAllSubordinateUserIds($item['user_id'],false,4);
  210. $teamTotalCount = count($teamUserIds);
  211. $teamPvSum = $this->dao->getTeamPvSum($item['user_id'],4);
  212. $item['team_total_count'] = $teamTotalCount;
  213. $item['team_pv_sum'] = $teamPvSum;
  214. // 补充用户信息
  215. if (isset($userMap[$item['user_id']])) {
  216. $item['nickname'] = $userMap[$item['user_id']]['nickname'];
  217. $item['avatar'] = $userMap[$item['user_id']]['avatar'];
  218. $item['create_time'] = $userMap[$item['user_id']]['create_time'];
  219. } else {
  220. $item['nickname'] = '';
  221. $item['avatar'] = '';
  222. $item['create_time'] = '';
  223. }
  224. // 找出团队业绩最大的直推用户
  225. if ($teamPvSum > $maxPv) {
  226. $maxPv = $teamPvSum;
  227. $maxPvIndex = $index;
  228. }
  229. }
  230. unset($item);
  231. // 分割大部门和小部门
  232. $bigDepartment = [];
  233. $smallDepartment = [];
  234. if ($maxPvIndex >= 0) {
  235. $bigDepartment[] = $list[$maxPvIndex];
  236. foreach ($list as $index => $item) {
  237. if ($index !== $maxPvIndex) {
  238. $smallDepartment[] = $item;
  239. }
  240. }
  241. } else {
  242. // 没有直推用户(理论上不会发生)
  243. $smallDepartment = $list;
  244. }
  245. // 计算统计数据
  246. $myTeamUserIds = $this->dao->getAllSubordinateUserIds($userId);
  247. $myTeamTotalCount = count($myTeamUserIds);
  248. $myTeamPvSum = $this->dao->getTeamPvSum($userId);
  249. $smallDepartmentPvSum = 0;
  250. foreach ($smallDepartment as $item) {
  251. $smallDepartmentPvSum += $item['team_pv_sum'];
  252. }
  253. $bigDepartmentPvSum = 0;
  254. foreach ($bigDepartment as $item) {
  255. $bigDepartmentPvSum += $item['team_pv_sum'];
  256. }
  257. return [
  258. 'all_direct' => $list,
  259. 'big_department' => $bigDepartment,
  260. 'small_department' => $smallDepartment,
  261. 'stats' => [
  262. 'my_team_total_count' => $myTeamTotalCount,
  263. 'my_team_pv_sum' => $myTeamPvSum,
  264. 'small_department_pv_sum' => floor($smallDepartmentPvSum * 100) / 100,
  265. 'big_department_pv_sum' => $bigDepartmentPvSum,
  266. ]
  267. ];
  268. }
  269. /**
  270. * 批量更新
  271. * @param $dataList
  272. * @return array
  273. */
  274. public function batchUpdateSharedProsperityUserDataByDataList($dataList): array
  275. {
  276. return $this->dao->saveAll($dataList);
  277. }
  278. /**
  279. * 用户身份升级
  280. * @param array $userIdList
  281. * @return void
  282. */
  283. public function identityUpgrade(array $userIdList)
  284. {
  285. if (empty($userIdList)) {
  286. return;
  287. }
  288. /** @var SharedProsperityRecommendConfigRepository $sharedProsperityRecommendConfigRepository */
  289. $sharedProsperityRecommendConfigRepository = app()->make(SharedProsperityRecommendConfigRepository::class);
  290. $sharedProsperityRecommendConfigEntityList = $sharedProsperityRecommendConfigRepository->getList();
  291. usort($sharedProsperityRecommendConfigEntityList, function (SharedProsperityRecommendConfigEntity $a, SharedProsperityRecommendConfigEntity $b) {
  292. return $a->getPv() <=> $b->getPv(); // 从小到大排序
  293. });
  294. $sharedProsperityUserEntityList = $this->getSharedProsperityUserEntityListByUserIdList($userIdList);
  295. // 批量更新用户等级
  296. $this->batchUpgradeUsers($sharedProsperityUserEntityList, $sharedProsperityRecommendConfigEntityList);
  297. // foreach ($sharedProsperityUserEntityList as $sharedProsperityUserEntity) {
  298. // $partnerLevel = 0;
  299. // foreach ($sharedProsperityRecommendConfigEntityList as $sharedProsperityRecommendConfigEntity) {
  300. // if ($sharedProsperityUserEntity->getPv() >= $sharedProsperityRecommendConfigEntity->getPv()) {
  301. // $partnerLevel = $sharedProsperityRecommendConfigEntity->getLevel();
  302. // } else {
  303. // // 如果本次验证的等级结果大于 之前的等级,说明用户升级了 需要更新等级
  304. // if ($partnerLevel > $sharedProsperityUserEntity->getPartnerLevel()) {
  305. // $this->updateByEntity(
  306. // SharedProsperityUserEntity::newInstance()
  307. // ->setId($sharedProsperityUserEntity->getId())
  308. // ->setPartnerLevel($partnerLevel)
  309. // );
  310. // }
  311. // break;
  312. // }
  313. // }
  314. // }
  315. }
  316. /**
  317. * 批量更新用户等级
  318. * @param SharedProsperityUserEntity[] $sharedProsperityUserEntityList 用户实体列表
  319. * @param SharedProsperityRecommendConfigEntity[] $sharedProsperityRecommendConfigEntityList 等级配置列表
  320. * @return void
  321. */
  322. private function batchUpgradeUsers(array $sharedProsperityUserEntityList, array $sharedProsperityRecommendConfigEntityList)
  323. {
  324. foreach ($sharedProsperityUserEntityList as $sharedProsperityUserEntity) {
  325. // // 计算用户的团队业绩(向下5级)
  326. // $teamPv = $this->calculateTeamPv($sharedProsperityUserEntity->getId());
  327. // 根据团队业绩确定等级
  328. // $newLevel = $this->calculateLevelByTeamPv($teamPv, $sharedProsperityRecommendConfigEntityList);
  329. //
  330. // // 如果新等级大于当前等级,则更新
  331. // if ($newLevel > $sharedProsperityUserEntity->getPartnerLevel()) {
  332. // $this->updateByEntity(
  333. // SharedProsperityUserEntity::newInstance()
  334. // ->setId($sharedProsperityUserEntity->getId())
  335. // ->setPartnerLevel($newLevel)
  336. // );
  337. // }
  338. $this->upgradeUpperLevels($sharedProsperityUserEntity->getUserId(), $sharedProsperityRecommendConfigEntityList);
  339. }
  340. }
  341. /**
  342. * 向上追溯更新上级身份等级(最多向上5层)
  343. * @param int $userId 当前用户ID
  344. * @param SharedProsperityRecommendConfigEntity[] $sharedProsperityRecommendConfigEntityList 等级配置列表
  345. * @return void
  346. */
  347. private function upgradeUpperLevels(int $userId, array $sharedProsperityRecommendConfigEntityList)
  348. {
  349. $maxLevels = SharedProsperityUserEnum::TEAM_DEPTH;
  350. $currentUserId = $userId;
  351. for ($i = 0; $i < $maxLevels; $i++) {
  352. // 获取上级用户ID
  353. $sharedProsperityUserEntity = $this->getSharedProsperityUserEntityByUserId($currentUserId);
  354. $parentId = $sharedProsperityUserEntity->getParentId();
  355. if (empty($parentId)) {
  356. break; // 没有上级,停止追溯
  357. }
  358. // 重新计算上级的团队业绩和等级
  359. $this->upgradeSingleUser($parentId, $sharedProsperityRecommendConfigEntityList);
  360. // 继续向上追溯
  361. $currentUserId = $parentId;
  362. }
  363. }
  364. /**
  365. * 升级单个用户身份
  366. * @param int $userId 用户ID
  367. * @param SharedProsperityRecommendConfigEntity[] $sharedProsperityRecommendConfigEntityList 等级配置列表
  368. * @return void
  369. */
  370. private function upgradeSingleUser(int $userId, array $sharedProsperityRecommendConfigEntityList)
  371. {
  372. // 获取用户实体
  373. $sharedProsperityUserEntity = $this->getSharedProsperityUserEntityByUserId($userId);
  374. if (empty($sharedProsperityUserEntity->getId())) {
  375. return;
  376. }
  377. // 计算团队业绩
  378. $teamPvMap = $this->calculateTeamPv($userId);
  379. // 当前只计算团队业绩的 小团队业绩
  380. $maxKey = array_keys($teamPvMap, max($teamPvMap))[0];
  381. unset($teamPvMap[$maxKey]);
  382. $teamPvBySmallSum = array_sum($teamPvMap);
  383. // 计算新等级
  384. $newLevel = $this->calculateLevelByTeamPv($teamPvBySmallSum, $sharedProsperityRecommendConfigEntityList);
  385. // 暂时新增加逻辑 用户购买 298 商品后,自动升级为1星合伙人,目前只有消费者 能够获得PV值,在奖励结算时,判断订单金额 是否大于 298 并且 用户身份为 用户,则升级为一星合伙人
  386. // 逻辑修改,如果用户的身份 是普通用户,则统计他在共富区内 所有消费的金额,是否超 每天自增的 升级限制金额,如果超过则升级为1星合伙人
  387. if ($sharedProsperityUserEntity->getPartnerLevel() == 0) {
  388. /** @var StoreOrderRepository $storeOrderRepository */
  389. $storeOrderRepository = app()->make(StoreOrderRepository::class);
  390. $sumTotalPrice = $storeOrderRepository->getSumTotalPriceByUidAndMerId($sharedProsperityUserEntity->getUserId(), CommonEnum::DESIGN_MERCHANT_ID['SharedProsperity']['code']);
  391. if (!empty($sumTotalPrice)) {
  392. /** @var SharedProsperityRecommendConfigRepository $sharedProsperityRecommendConfigRepository */
  393. $sharedProsperityRecommendConfigRepository = app()->make(SharedProsperityRecommendConfigRepository::class);
  394. $sharedProsperityRecommendConfigEntityList = $sharedProsperityRecommendConfigRepository->getList();
  395. usort($sharedProsperityRecommendConfigEntityList, function (SharedProsperityRecommendConfigEntity $a, SharedProsperityRecommendConfigEntity $b) {
  396. return $a->getLevel() <=> $b->getLevel(); // 从小到大排序
  397. });
  398. foreach ($sharedProsperityRecommendConfigEntityList as $sharedProsperityRecommendConfigEntity) {
  399. if (is_null($sharedProsperityRecommendConfigEntity->getConsume())) {
  400. continue;
  401. }
  402. if ($sumTotalPrice >= $sharedProsperityRecommendConfigEntity->getConsume() && $newLevel < $sharedProsperityRecommendConfigEntity->getLevel()) {
  403. $newLevel = $sharedProsperityRecommendConfigEntity->getLevel();
  404. }
  405. }
  406. }
  407. }
  408. // 如果新等级大于当前等级,则更新
  409. if ($newLevel > $sharedProsperityUserEntity->getPartnerLevel()) {
  410. $this->updateByEntity(
  411. SharedProsperityUserEntity::newInstance()
  412. ->setId($sharedProsperityUserEntity->getId())
  413. ->setPartnerLevel($newLevel)
  414. );
  415. }
  416. }
  417. /**
  418. * 计算用户的团队业绩(向下5级)
  419. * @param int $userId 用户ID
  420. * @return array 团队业绩
  421. */
  422. private function calculateTeamPv(int $userId): array
  423. {
  424. $teamPvMap = [];
  425. // 获取所有下级用户ID(向下5级)
  426. // 第一层级在这里查询 因为要统计大小区
  427. $sharedProsperityUserEntityListByParentId = $this->getSharedProsperityUserEntityListByParentId($userId);
  428. // 循环 直属下级
  429. foreach ($sharedProsperityUserEntityListByParentId as $sharedProsperityUserEntityByUnderling) {
  430. $departmentTeamUserIdList = $this->getUserIdListByParentIdForDepth($sharedProsperityUserEntityByUnderling->getUserId(), SharedProsperityUserEnum::TEAM_DEPTH - 1);
  431. $departmentTeamUserIdList[] = $sharedProsperityUserEntityByUnderling->getUserId();
  432. // 直属团队的 业绩总和
  433. $teamPv = '0.00';
  434. if (!empty($departmentTeamUserIdList)) {
  435. // 批量获取下级用户的个人业绩并求和
  436. // 假设有方法批量获取用户的PV
  437. $sharedProsperityUserEntityListByTeam = $this->getSharedProsperityUserEntityListByUserIdList($departmentTeamUserIdList);
  438. foreach ($sharedProsperityUserEntityListByTeam as $sharedProsperityUserEntityByTeam) {
  439. $teamPv = bcadd($teamPv, (string)$sharedProsperityUserEntityByTeam->getPv(), 2);
  440. }
  441. }
  442. $teamPvMap[$sharedProsperityUserEntityByUnderling->getUserId()] = $teamPv;
  443. }
  444. return $teamPvMap;
  445. }
  446. /**
  447. * 根据团队业绩计算等级
  448. * @param float $teamPv 团队业绩
  449. * @param array $configEntityList 等级配置列表
  450. * @return int 等级
  451. */
  452. private function calculateLevelByTeamPv(float $teamPv, array $configEntityList): int
  453. {
  454. $level = 0;
  455. foreach ($configEntityList as $configEntity) {
  456. if ($teamPv >= $configEntity->getPv()) {
  457. $level = $configEntity->getLevel();
  458. } else {
  459. break;
  460. }
  461. }
  462. return $level;
  463. }
  464. /**
  465. * 获取下级用户ID列表(向下指定层级)
  466. * @param int $parentId 用户ID
  467. * @param int $maxLevel 最大层级数
  468. * @param int $currentLevel 当前层级(内部递归使用)
  469. * @return array 下级用户ID列表
  470. */
  471. private function getUserIdListByParentIdForDepth(int $parentId, int $maxLevel, int $currentLevel = 1): array
  472. {
  473. if ($currentLevel > $maxLevel) {
  474. return [];
  475. }
  476. $subordinateIds = [];
  477. // 获取直接下级用户ID列表(假设有方法获取直接下级)
  478. $sharedProsperityUserEntityListByParentId = $this->getSharedProsperityUserEntityListByParentId($parentId);
  479. if (empty($sharedProsperityUserEntityListByParentId)) {
  480. return [];
  481. }
  482. // 添加直接下级
  483. $subordinateIds = array_merge($subordinateIds, array_column($sharedProsperityUserEntityListByParentId, 'userId'));
  484. // 递归获取下级的下级
  485. foreach ($sharedProsperityUserEntityListByParentId as $sharedProsperityUserEntity) {
  486. $nestedSubordinateIds = $this->getUserIdListByParentIdForDepth($sharedProsperityUserEntity->getUserId(), $maxLevel, $currentLevel + 1);
  487. if (!empty($nestedSubordinateIds)) {
  488. $subordinateIds = array_merge($subordinateIds, $nestedSubordinateIds);
  489. }
  490. }
  491. return array_unique($subordinateIds);
  492. }
  493. /**
  494. * 获取用户树
  495. * @param int $userId 用户ID
  496. * @return array 用户树,格式:[{name: '张三', parent: null, children: [...]}]
  497. */
  498. public function getUserTree($userId)
  499. {
  500. /** @var SharedProsperityUserDao $shareUserDao */
  501. $shareUserDao = app()->make(SharedProsperityUserDao::class);
  502. // 获取所有下级用户ID(包括自己)
  503. $subordinateIds = $shareUserDao->getAllSubordinateUserIds($userId, true);
  504. if (empty($subordinateIds)) {
  505. return [];
  506. }
  507. // 获取这些共富用户的基本信息(包含parent_id)
  508. $sharedUsers = $shareUserDao->getSharedProsperityUserEntityListByUserIdList($subordinateIds);
  509. if (empty($sharedUsers)) {
  510. return [];
  511. }
  512. // 用户身份
  513. $partnerLevel = [
  514. 0 => '用户',
  515. 1 => '一星合伙人',
  516. 2 => '二星合伙人',
  517. 3 => '三星合伙人',
  518. 4 => '钻石合伙人',
  519. 5 => '总裁合伙人',
  520. 6 => '联席主席团',
  521. ];
  522. // 获取用户昵称映射
  523. $userIds = array_map(function ($entity) {
  524. return $entity->getUserId();
  525. }, $sharedUsers);
  526. /** @var UserDao $userDao */
  527. $userDao = app()->make(UserDao::class);
  528. $userInfos = $userDao->getUserEntityListByUidList($userIds);
  529. $idToName = [];
  530. foreach ($userInfos as $userInfo) {
  531. $sharedUserInfo = $shareUserDao->getSharedProsperityUserEntityListByUserIdList([$userInfo->getUid()]);
  532. $idToName[$userInfo->getUid()] = $userInfo->getNickname() . '(' . $userInfo->account .')(身份:' . $partnerLevel[$sharedUserInfo[0]->getPartnerLevel()] . ')' ?? ('用户' . $userInfo->getUid());
  533. }
  534. // 构建节点数组
  535. $nodes = [];
  536. foreach ($sharedUsers as $sharedUser) {
  537. $nodes[] = [
  538. 'user_id' => $sharedUser->getUserId(),
  539. 'parent_id' => $sharedUser->getParentId(),
  540. 'name' => $idToName[$sharedUser->getUserId()] ?? ('用户' . $sharedUser->getUserId()),
  541. ];
  542. }
  543. // 构建树,以传入的用户为根节点
  544. $rootNode = $this->findNode($nodes, $userId);
  545. if (!$rootNode) {
  546. return [];
  547. }
  548. $tree = [
  549. 'name' => $rootNode['name'],
  550. 'parent' => null,
  551. 'children' => $this->buildSharedTree($nodes, $userId)
  552. ];
  553. return [$tree];
  554. }
  555. /**
  556. * 递归构建共富用户树
  557. * @param array $nodes 节点数组,每个节点包含 user_id, parent_id, name
  558. * @param int $parentId 父ID
  559. * @return array
  560. */
  561. private function buildSharedTree($nodes, $parentId)
  562. {
  563. $branch = [];
  564. foreach ($nodes as $node) {
  565. if ($node['parent_id'] == $parentId) {
  566. $children = $this->buildSharedTree($nodes, $node['user_id']);
  567. $branch[] = [
  568. 'name' => $node['name'],
  569. 'parent' => $this->findNodeName($nodes, $parentId) ?? null,
  570. 'children' => $children
  571. ];
  572. }
  573. }
  574. return $branch;
  575. }
  576. /**
  577. * 根据user_id查找节点名称
  578. * @param array $nodes
  579. * @param int $userId
  580. * @return string|null
  581. */
  582. private function findNodeName($nodes, $userId)
  583. {
  584. foreach ($nodes as $node) {
  585. if ($node['user_id'] == $userId) {
  586. return $node['name'];
  587. }
  588. }
  589. return null;
  590. }
  591. /**
  592. * 根据user_id查找节点
  593. * @param array $nodes
  594. * @param int $userId
  595. * @return array|null
  596. */
  597. private function findNode($nodes, $userId)
  598. {
  599. foreach ($nodes as $node) {
  600. if ($node['user_id'] == $userId) {
  601. return $node;
  602. }
  603. }
  604. return null;
  605. }
  606. public function adminList($params)
  607. {
  608. $page = $params['page'] ?? 1;
  609. $where = [];
  610. /** @var UserDao $userDao */
  611. $userDao = app()->make(UserDao::class);
  612. // 手机号搜索
  613. if (isset($params['account']) && $params['account']) {
  614. $userData = $userDao->accountByUser($params['account']);
  615. $uid = 0;
  616. if ($userData) {
  617. $uid = $userData->uid;
  618. }
  619. $where[] = ['user_id', '=', $uid];
  620. }
  621. // 昵称搜索
  622. if (isset($params['nickname']) && $params['nickname']) {
  623. $userData = $userDao->nicknameByUser($params['nickname']);
  624. $uid = 0;
  625. if ($userData) {
  626. $uid = $userData->uid;
  627. }
  628. $where[] = ['user_id', '=', $uid];
  629. }
  630. // 合伙人等级搜索
  631. if (isset($params['partner_level']) && $params['partner_level']) {
  632. $where[] = ['partner_level', '=', $params['partner_level']];
  633. }
  634. // 共富团等级搜索
  635. if (isset($params['user_group']) && $params['user_group']) {
  636. /** @var SharedProsperityGroupUserDao $groupUserDao */
  637. $groupUserDao = app()->make(SharedProsperityGroupUserDao::class);
  638. $groupUserData = $groupUserDao->getUserByLevel($params['user_group']);
  639. $uids = array_column($groupUserData['data'], 'user_id');
  640. $where[] = ['user_id', 'in', $uids];
  641. $page = 1;
  642. }
  643. $list = $this->dao->adminList($where, $page);
  644. return $list;
  645. }
  646. /**
  647. * @param $userId
  648. * @param $level
  649. * @return int
  650. * @author 史晨
  651. * @date 2026/2/27 14:23
  652. * 更新用户等级
  653. */
  654. public function updateLevel($userId, $level)
  655. {
  656. return $this->dao->updateByUserId($userId, ['partner_level' => $level]);
  657. }
  658. /**
  659. * @param $userId
  660. * @param $type
  661. * @param $number
  662. * @return bool
  663. * @author 史晨
  664. * @date 2026/2/27 15:16
  665. * 更新用户奖励
  666. */
  667. public function updateReward($userId, $type, $number)
  668. {
  669. $map = [
  670. 1001 => 'consumer_stocks',
  671. 1002 => 'withdrawal_limit',
  672. 1003 => 'pv'
  673. ];
  674. try {
  675. Db::startTrans();
  676. $pm = 1;
  677. $remark = '后台操作增加' . $number;
  678. if ($number < 0) {
  679. $pm = 0;
  680. $remark = '后台操作减少' . abs($number);
  681. }
  682. if (isset($map[$type])) {
  683. // 更新数据
  684. $this->dao->updateRewardByUserId($userId, $map[$type], $number);
  685. // 记录日志
  686. $insertData = [
  687. 'user_id' => $userId,
  688. 'type' => $type,
  689. 'pm' => $pm,
  690. 'number' => abs($number),
  691. 'balance' => 0,
  692. 'status' => SharedProsperityRewardRecordEnum::STATUS['VALID']['code'],
  693. 'type_shop' => SharedProsperityRewardRecordEnum::TYPE_SHOP['Platform']['code'],
  694. 'order_sn' => 0,
  695. 'take_time' => date('Y-m-d H:i:s', time()),
  696. 'remark' => $remark,
  697. 'create_time' => date('Y-m-d H:i:s', time()),
  698. 'update_time' => date('Y-m-d H:i:s', time()),
  699. ];
  700. /** @var SharedProsperityRewardRecordDao $rewardRecordDao */
  701. $rewardRecordDao = app()->make(SharedProsperityRewardRecordDao::class);
  702. $rewardRecordDao->insertAll([$insertData]);
  703. } else {
  704. // 更新数据
  705. /** @var UserDao $userDao */
  706. $userDao = app()->make(UserDao::class);
  707. $userDao->updateBrokeragePriceByUid($userId, $number);;
  708. // 记录日志
  709. $bill = [
  710. 'uid' => $userId,
  711. 'link_id' => 0,
  712. 'pm' => $pm,
  713. 'title' => $remark,
  714. 'category' => 'now_money',
  715. 'type' => 'commission',
  716. 'number' => abs($number),
  717. 'balance' => 0,
  718. 'mark' => $remark,
  719. 'create_time' => date('Y-m-d H:i:s'),
  720. 'status' => 1,
  721. 'commission_type' => CommonEnum::COMMISSION_TYPE['SHARED_PROSPERITY_PARTNER_COMMISSION']['code'],
  722. 'order_sn' => 0,
  723. 'tripartite' => 0,
  724. 'type_shop' => 0,
  725. 'mer_id' => 0,
  726. 'source' => 0,
  727. 'order_type' => 1,
  728. 'is_red_brokerage' => 0,
  729. 'gzc' => 3,
  730. 'take_time' => time(),
  731. 'district_id' => '',
  732. 'street_id' => '',
  733. 'month' => '',
  734. ];
  735. Db::name('user_bill')->insert($bill);
  736. }
  737. Db::commit();
  738. return true;
  739. } catch (\Exception $e) {
  740. Db::rollback();
  741. return false;
  742. }
  743. }
  744. }