SharedProsperityUserRepository.php 42 KB

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