SharedProsperityUserRepository.php 31 KB

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