SharedProsperityUserRepository.php 40 KB

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