SharedProsperityUserRepository.php 43 KB

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