| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047 |
- <?php
- namespace app\common\repositories\shared;
- use app\common\dao\shared\SharedProsperityGroupUserDao;
- use app\common\dao\shared\SharedProsperityRewardRecordDao;
- use app\common\dao\shared\SharedProsperityUserDao;
- use app\common\dao\shared\SharedProsperityUserLevelLogDao;
- use app\common\dao\user\UserDao;
- use app\common\dao\user\UserWithdrawalLimitRecordDao;
- use app\common\enum\CommonEnum;
- use app\common\enum\shared\SharedProsperityRewardRecordEnum;
- use app\common\enum\shared\SharedProsperityUserEnum;
- use app\common\repositories\BaseRepository;
- use app\common\repositories\store\order\StoreOrderRepository;
- use app\entity\data\shared\SharedProsperityGroupUserEntity;
- use app\entity\data\shared\SharedProsperityRecommendConfigEntity;
- use app\entity\data\shared\SharedProsperityUserEntity;
- use think\db\exception\DbException;
- use think\facade\Db;
- class SharedProsperityUserRepository extends BaseRepository
- {
- protected $dao;
- /**
- * SharedProsperityUserRepository constructor.
- * @param SharedProsperityUserDao $dao
- */
- public function __construct(SharedProsperityUserDao $dao)
- {
- $this->dao = $dao;
- }
- /**
- * @param int $id
- * @return SharedProsperityUserEntity
- */
- public function getSharedProsperityUserEntityById(int $id): SharedProsperityUserEntity
- {
- $entityList = $this->getSharedProsperityUserEntityListByIdList([$id]);
- $entity = array_shift($entityList);
- if ($entity instanceof SharedProsperityUserEntity) {
- return $entity;
- } else {
- /** @var SharedProsperityUserEntity */
- return SharedProsperityUserEntity::newInstance();
- }
- }
- /**
- * @param array $idList
- * @return SharedProsperityUserEntity[]
- */
- public function getSharedProsperityUserEntityListByIdList(array $idList): array
- {
- return $this->dao->getSharedProsperityUserEntityListByIdList($idList);
- }
- /**
- * @param int $userId
- * @return SharedProsperityUserEntity
- */
- public function getSharedProsperityUserEntityByUserId(int $userId): SharedProsperityUserEntity
- {
- $entityList = $this->getSharedProsperityUserEntityListByUserIdList([$userId]);
- $entity = array_shift($entityList);
- if ($entity instanceof SharedProsperityUserEntity) {
- return $entity;
- } else {
- /** @var SharedProsperityUserEntity */
- return SharedProsperityUserEntity::newInstance();
- }
- }
- /**
- * @param array $userIdList
- * @return SharedProsperityUserEntity[]
- */
- public function getSharedProsperityUserEntityListByUserIdList(array $userIdList): array
- {
- return $this->dao->getSharedProsperityUserEntityListByUserIdList($userIdList);
- }
- /**
- * 获取直接下级用户ID列表
- * @param int $parentId 用户ID
- * @return SharedProsperityUserEntity[] 直接下级用户ID列表
- */
- public function getSharedProsperityUserEntityListByParentId(int $parentId): array
- {
- return $this->dao->getSharedProsperityUserEntityListByParentId($parentId);
- }
- /**
- * @param array $userIdList
- * @return SharedProsperityUserEntity[]
- */
- public function getSharedProsperityUserEntityMapByUserIdList(array $userIdList): array
- {
- $sharedProsperityUserEntityList = $this->dao->getSharedProsperityUserEntityListByUserIdList($userIdList);
- /** @var SharedProsperityUserEntity[] $sharedProsperityUserEntityMapByUserId */
- $sharedProsperityUserEntityMapByUserId = array_column($sharedProsperityUserEntityList, null, 'userId');
- return $sharedProsperityUserEntityMapByUserId;
- }
- public function create($data)
- {
- return $this->dao->create($data);
- }
- /**
- * @param SharedProsperityUserEntity $sharedProsperityUserEntity
- * @return SharedProsperityUserEntity
- */
- public function createByEntity(SharedProsperityUserEntity $sharedProsperityUserEntity): SharedProsperityUserEntity
- {
- $result = $this->create($sharedProsperityUserEntity->toUnderlineArray())->toArray();
- /** @var SharedProsperityUserEntity $entity */
- $entity = SharedProsperityUserEntity::newInstance($result);
- return $entity;
- }
- /**
- * @param $id
- * @param $data
- * @return int
- */
- public function update($id, $data): int
- {
- try {
- return $this->dao->update($id, $data);
- } catch (DbException $e) {
- return 0;
- }
- }
- public function updateByUserId($userId, $data): int
- {
- try {
- return $this->dao->updateByUserId($userId, $data);
- } catch (DbException $e) {
- return 0;
- }
- }
- /**
- * @param SharedProsperityUserEntity $sharedProsperityUserEntity
- * @return SharedProsperityUserEntity
- */
- public function updateByEntity(SharedProsperityUserEntity $sharedProsperityUserEntity): SharedProsperityUserEntity
- {
- if (empty($sharedProsperityUserEntity->getId())) {
- return SharedProsperityUserEntity::newInstance();
- }
- $result = $this->update($sharedProsperityUserEntity->getId(), $sharedProsperityUserEntity->toUnderlineArray());
- if ($result > 0) {
- return $this->getSharedProsperityUserEntityById($sharedProsperityUserEntity->getId());
- }
- return SharedProsperityUserEntity::newInstance();
- }
- /**
- * 绑定 上级
- * @param int $userId
- * @param int $parentId
- * @return bool
- */
- public function bindParentId(int $userId, int $parentId): bool
- {
- $sharedProsperityUserEntity = $this->getSharedProsperityUserEntityByUserId($userId);
- if (empty($sharedProsperityUserEntity->getUserId())) {
- return false;
- }
- $sharedProsperityUserEntityByParentId = $this->getSharedProsperityUserEntityByUserId($parentId);
- if (empty($sharedProsperityUserEntityByParentId->getUserId())) {
- return false;
- }
- $sharedProsperityUserEntity = $this->updateByEntity($sharedProsperityUserEntity->setParentId($sharedProsperityUserEntityByParentId->getUserId()));
- if (empty($sharedProsperityUserEntity->getId())) {
- return false;
- }
- return true;
- }
- /**
- * 获取直推用户列表,并计算每个直推用户的团队总人数和团队总业绩(包含自己)
- * 返回三个列表:全部直推、大部门(团队业绩最大的直推用户)、小部门(其余直推用户)
- * 同时返回统计数据:我的部门总人数、总业绩、小部门业绩总和、大部门业绩总和
- * @param int $userId
- * @return array
- */
- public function getTeam(int $userId): array
- {
- // 获取直推用户
- $list = $this->dao->getDirectByUserId($userId);
- if (empty($list)) {
- // 没有直推用户,仍然返回统计数据(我的部门总人数和总业绩)
- $myTeamUserIds = $this->dao->getAllSubordinateUserIds($userId);
- $myTeamTotalCount = count($myTeamUserIds);
- $myTeamPvSum = $this->dao->getTeamPvSumWithSelf($userId);
- return [
- 'all_direct' => [],
- 'big_department' => [],
- 'small_department' => [],
- 'stats' => [
- 'my_team_total_count' => $myTeamTotalCount,
- 'my_team_pv_sum' => $myTeamPvSum,
- 'small_department_pv_sum' => 0,
- 'big_department_pv_sum' => 0,
- ]
- ];
- }
- // 收集所有直推用户ID
- $userIds = array_column($list, 'user_id');
- // 获取用户详细信息(昵称、头像、注册时间)
- /** @var UserDao $userDao */
- $userDao = app()->make(UserDao::class);
- $userEntities = $userDao->getUserEntityListByUidList($userIds);
- $userMap = [];
- foreach ($userEntities as $userEntity) {
- $userMap[$userEntity->getUid()] = [
- 'nickname' => $userEntity->getNickname(),
- 'avatar' => $userEntity->getAvatar(),
- 'create_time' => $userEntity->getCreateTime(),
- ];
- }
- // 计算每个直推用户的团队总人数和团队总业绩
- $maxPv = 0;
- $maxPvIndex = -1;
- foreach ($list as $index => &$item) {
- $teamUserIds = $this->dao->getAllSubordinateUserIds($item['user_id'], false, 4);
- $teamTotalCount = count($teamUserIds);
- $teamPvSum = $this->dao->getTeamPvSum($item['user_id'], 4);
- $item['team_total_count'] = $teamTotalCount;
- $item['team_pv_sum'] = $teamPvSum;
- // 补充用户信息
- if (isset($userMap[$item['user_id']])) {
- $item['nickname'] = $userMap[$item['user_id']]['nickname'];
- $item['avatar'] = $userMap[$item['user_id']]['avatar'];
- $item['create_time'] = $userMap[$item['user_id']]['create_time'];
- } else {
- $item['nickname'] = '';
- $item['avatar'] = '';
- $item['create_time'] = '';
- }
- // 找出团队业绩最大的直推用户
- if ($teamPvSum > $maxPv) {
- $maxPv = $teamPvSum;
- $maxPvIndex = $index;
- }
- }
- unset($item);
- // 分割大部门和小部门
- $bigDepartment = [];
- $smallDepartment = [];
- if ($maxPvIndex >= 0) {
- $bigDepartment[] = $list[$maxPvIndex];
- foreach ($list as $index => $item) {
- if ($index !== $maxPvIndex) {
- $smallDepartment[] = $item;
- }
- }
- } else {
- // 没有直推用户(理论上不会发生)
- $smallDepartment = $list;
- }
- // 计算统计数据
- $myTeamUserIds = $this->dao->getAllSubordinateUserIds($userId);
- $myTeamTotalCount = count($myTeamUserIds);
- $myTeamPvSum = $this->dao->getTeamPvSum($userId);
- $smallDepartmentPvSum = 0;
- foreach ($smallDepartment as $item) {
- $smallDepartmentPvSum += $item['team_pv_sum'];
- }
- $bigDepartmentPvSum = 0;
- foreach ($bigDepartment as $item) {
- $bigDepartmentPvSum += $item['team_pv_sum'];
- }
- return [
- 'all_direct' => $list,
- 'big_department' => $bigDepartment,
- 'small_department' => $smallDepartment,
- 'stats' => [
- 'my_team_total_count' => $myTeamTotalCount,
- 'my_team_pv_sum' => $myTeamPvSum,
- 'small_department_pv_sum' => floor($smallDepartmentPvSum * 100) / 100,
- 'big_department_pv_sum' => $bigDepartmentPvSum,
- ]
- ];
- }
- /**
- * 批量更新
- * @param $dataList
- * @return array
- */
- public function batchUpdateSharedProsperityUserDataByDataList($dataList): array
- {
- return $this->dao->saveAll($dataList);
- }
- /**
- * 用户身份升级
- * @param array $userIdList
- * @return void
- */
- public function identityUpgrade(array $userIdList)
- {
- if (empty($userIdList)) {
- return;
- }
- /** @var SharedProsperityRecommendConfigRepository $sharedProsperityRecommendConfigRepository */
- $sharedProsperityRecommendConfigRepository = app()->make(SharedProsperityRecommendConfigRepository::class);
- $sharedProsperityRecommendConfigEntityList = $sharedProsperityRecommendConfigRepository->getList();
- usort($sharedProsperityRecommendConfigEntityList, function (SharedProsperityRecommendConfigEntity $a, SharedProsperityRecommendConfigEntity $b) {
- return $a->getPv() <=> $b->getPv(); // 从小到大排序
- });
- $sharedProsperityUserEntityList = $this->getSharedProsperityUserEntityListByUserIdList($userIdList);
- // 批量更新用户等级
- $this->batchUpgradeUsers($sharedProsperityUserEntityList, $sharedProsperityRecommendConfigEntityList);
- // foreach ($sharedProsperityUserEntityList as $sharedProsperityUserEntity) {
- // $partnerLevel = 0;
- // foreach ($sharedProsperityRecommendConfigEntityList as $sharedProsperityRecommendConfigEntity) {
- // if ($sharedProsperityUserEntity->getPv() >= $sharedProsperityRecommendConfigEntity->getPv()) {
- // $partnerLevel = $sharedProsperityRecommendConfigEntity->getLevel();
- // } else {
- // // 如果本次验证的等级结果大于 之前的等级,说明用户升级了 需要更新等级
- // if ($partnerLevel > $sharedProsperityUserEntity->getPartnerLevel()) {
- // $this->updateByEntity(
- // SharedProsperityUserEntity::newInstance()
- // ->setId($sharedProsperityUserEntity->getId())
- // ->setPartnerLevel($partnerLevel)
- // );
- // }
- // break;
- // }
- // }
- // }
- }
- /**
- * 批量更新用户等级
- * @param SharedProsperityUserEntity[] $sharedProsperityUserEntityList 用户实体列表
- * @param SharedProsperityRecommendConfigEntity[] $sharedProsperityRecommendConfigEntityList 等级配置列表
- * @return void
- */
- private function batchUpgradeUsers(array $sharedProsperityUserEntityList, array $sharedProsperityRecommendConfigEntityList)
- {
- foreach ($sharedProsperityUserEntityList as $sharedProsperityUserEntity) {
- // // 计算用户的团队业绩(向下5级)
- // $teamPv = $this->calculateTeamPv($sharedProsperityUserEntity->getId());
- // 根据团队业绩确定等级
- // $newLevel = $this->calculateLevelByTeamPv($teamPv, $sharedProsperityRecommendConfigEntityList);
- //
- // // 如果新等级大于当前等级,则更新
- // if ($newLevel > $sharedProsperityUserEntity->getPartnerLevel()) {
- // $this->updateByEntity(
- // SharedProsperityUserEntity::newInstance()
- // ->setId($sharedProsperityUserEntity->getId())
- // ->setPartnerLevel($newLevel)
- // );
- // }
- // 暂时新增加逻辑 用户购买 298 商品后,自动升级为1星合伙人,目前只有消费者 能够获得PV值,在奖励结算时,判断订单金额 是否大于 298 并且 用户身份为 用户,则升级为一星合伙人
- // 逻辑修改,如果用户的身份 是普通用户,则统计他在共富区内 所有消费的金额,是否超 每天自增的 升级限制金额,如果超过则升级为1星合伙人
- if ($sharedProsperityUserEntity->getPartnerLevel() == 0) {
- /** @var StoreOrderRepository $storeOrderRepository */
- $storeOrderRepository = app()->make(StoreOrderRepository::class);
- $sumTotalPrice = $storeOrderRepository->getSumTotalPriceByUidAndMerId($sharedProsperityUserEntity->getUserId(), CommonEnum::DESIGN_MERCHANT_ID['SharedProsperity']['code']);
- if (!empty($sumTotalPrice)) {
- $partnerLevel = $sharedProsperityUserEntity->getPartnerLevel();
- /** @var SharedProsperityRecommendConfigRepository $sharedProsperityRecommendConfigRepository */
- $sharedProsperityRecommendConfigRepository = app()->make(SharedProsperityRecommendConfigRepository::class);
- $sharedProsperityRecommendConfigEntityList = $sharedProsperityRecommendConfigRepository->getList();
- usort($sharedProsperityRecommendConfigEntityList, function (SharedProsperityRecommendConfigEntity $a, SharedProsperityRecommendConfigEntity $b) {
- return $a->getLevel() <=> $b->getLevel(); // 从小到大排序
- });
- foreach ($sharedProsperityRecommendConfigEntityList as $sharedProsperityRecommendConfigEntity) {
- if (is_null($sharedProsperityRecommendConfigEntity->getConsume())) {
- continue;
- }
- if ($sumTotalPrice >= $sharedProsperityRecommendConfigEntity->getConsume() && $sharedProsperityUserEntity->getPartnerLevel() < $sharedProsperityRecommendConfigEntity->getLevel()) {
- // 修改用户的等级
- $sharedProsperityUserEntity->setPartnerLevel($sharedProsperityRecommendConfigEntity->getLevel());
- }
- }
- // 也就是说 升级了 保存到数据库
- if ($partnerLevel != $sharedProsperityUserEntity->getPartnerLevel()) {
- $this->updateByEntity(
- SharedProsperityUserEntity::newInstance()
- ->setId($sharedProsperityUserEntity->getId())
- ->setPartnerLevel($sharedProsperityUserEntity->getPartnerLevel())
- );
- }
- }
- }
- // 根据原来的团队升级规则,去升级推荐人等级
- $this->upgradeUpperLevels($sharedProsperityUserEntity->getUserId(), $sharedProsperityRecommendConfigEntityList);
- // 新的升级规则
- // 如果当前用户升级了 那要看一下他的上级 是否也需要升级
- if (!empty($sharedProsperityUserEntity->getParentId())) {
- $sharedProsperityUserEntityByParent = $this->getSharedProsperityUserEntityByUserId($sharedProsperityUserEntity->getParentId());
- if (!empty($sharedProsperityUserEntityByParent->getId()) && $sharedProsperityUserEntityByParent->getPartnerLevel() < 2) {
- $this->upgradeUpperLevelsByPromotionOne($sharedProsperityUserEntityByParent);
- }
- }
- }
- }
- /**
- * 向上追溯更新上级身份等级(最多向上5层)
- * @param int $userId 当前用户ID
- * @param SharedProsperityRecommendConfigEntity[] $sharedProsperityRecommendConfigEntityList 等级配置列表
- * @return void
- */
- private function upgradeUpperLevels(int $userId, array $sharedProsperityRecommendConfigEntityList)
- {
- $maxLevels = SharedProsperityUserEnum::TEAM_DEPTH;
- $currentUserId = $userId;
- for ($i = 0; $i < $maxLevels; $i++) {
- // 获取上级用户ID
- $sharedProsperityUserEntity = $this->getSharedProsperityUserEntityByUserId($currentUserId);
- $parentId = $sharedProsperityUserEntity->getParentId();
- if (empty($parentId)) {
- break; // 没有上级,停止追溯
- }
- // 重新计算上级的团队业绩和等级
- $this->upgradeSingleUser($parentId, $sharedProsperityRecommendConfigEntityList);
- // 继续向上追溯
- $currentUserId = $parentId;
- }
- }
- /**
- * 升级单个用户身份
- * @param int $userId 用户ID
- * @param SharedProsperityRecommendConfigEntity[] $sharedProsperityRecommendConfigEntityList 等级配置列表
- * @return void
- */
- private function upgradeSingleUser(int $userId, array $sharedProsperityRecommendConfigEntityList)
- {
- // 获取用户实体
- $sharedProsperityUserEntity = $this->getSharedProsperityUserEntityByUserId($userId);
- if (empty($sharedProsperityUserEntity->getId())) {
- return;
- }
- // 计算团队业绩
- $teamPvMap = $this->calculateTeamPv($userId);
- // 当前只计算团队业绩的 小团队业绩
- $maxKey = array_keys($teamPvMap, max($teamPvMap))[0];
- unset($teamPvMap[$maxKey]);
- $teamPvBySmallSum = array_sum($teamPvMap);
- // 计算新等级
- $newLevel = $this->calculateLevelByTeamPv($teamPvBySmallSum, $sharedProsperityRecommendConfigEntityList);
- // 如果新等级大于当前等级,则更新
- if ($newLevel > $sharedProsperityUserEntity->getPartnerLevel()) {
- $this->updateByEntity(
- SharedProsperityUserEntity::newInstance()
- ->setId($sharedProsperityUserEntity->getId())
- ->setPartnerLevel($newLevel)
- );
- }
- }
- /**
- * 计算用户的团队业绩(向下5级)
- * @param int $userId 用户ID
- * @return array 团队业绩
- */
- private function calculateTeamPv(int $userId): array
- {
- $teamPvMap = [];
- // 获取所有下级用户ID(向下5级)
- // 第一层级在这里查询 因为要统计大小区
- $sharedProsperityUserEntityListByParentId = $this->getSharedProsperityUserEntityListByParentId($userId);
- // 循环 直属下级
- foreach ($sharedProsperityUserEntityListByParentId as $sharedProsperityUserEntityByUnderling) {
- $departmentTeamUserIdList = $this->getUserIdListByParentIdForDepth($sharedProsperityUserEntityByUnderling->getUserId(), SharedProsperityUserEnum::TEAM_DEPTH - 1);
- $departmentTeamUserIdList[] = $sharedProsperityUserEntityByUnderling->getUserId();
- // 直属团队的 业绩总和
- $teamPv = '0.00';
- if (!empty($departmentTeamUserIdList)) {
- // 批量获取下级用户的个人业绩并求和
- // 假设有方法批量获取用户的PV
- $sharedProsperityUserEntityListByTeam = $this->getSharedProsperityUserEntityListByUserIdList($departmentTeamUserIdList);
- foreach ($sharedProsperityUserEntityListByTeam as $sharedProsperityUserEntityByTeam) {
- $teamPv = bcadd($teamPv, (string)$sharedProsperityUserEntityByTeam->getPv(), 2);
- }
- }
- $teamPvMap[$sharedProsperityUserEntityByUnderling->getUserId()] = $teamPv;
- }
- return $teamPvMap;
- }
- /**
- * 根据团队业绩计算等级
- * @param float $teamPv 团队业绩
- * @param array $configEntityList 等级配置列表
- * @return int 等级
- */
- private function calculateLevelByTeamPv(float $teamPv, array $configEntityList): int
- {
- $level = 0;
- foreach ($configEntityList as $configEntity) {
- if ($teamPv >= $configEntity->getPv()) {
- $level = $configEntity->getLevel();
- } else {
- break;
- }
- }
- return $level;
- }
- /**
- * 获取下级用户ID列表(向下指定层级)
- * @param int $parentId 用户ID
- * @param int $maxLevel 最大层级数
- * @param int $currentLevel 当前层级(内部递归使用)
- * @return array 下级用户ID列表
- */
- private function getUserIdListByParentIdForDepth(int $parentId, int $maxLevel, int $currentLevel = 1): array
- {
- if ($currentLevel > $maxLevel) {
- return [];
- }
- $subordinateIds = [];
- // 获取直接下级用户ID列表(假设有方法获取直接下级)
- $sharedProsperityUserEntityListByParentId = $this->getSharedProsperityUserEntityListByParentId($parentId);
- if (empty($sharedProsperityUserEntityListByParentId)) {
- return [];
- }
- // 添加直接下级
- $subordinateIds = array_merge($subordinateIds, array_column($sharedProsperityUserEntityListByParentId, 'userId'));
- // 递归获取下级的下级
- foreach ($sharedProsperityUserEntityListByParentId as $sharedProsperityUserEntity) {
- $nestedSubordinateIds = $this->getUserIdListByParentIdForDepth($sharedProsperityUserEntity->getUserId(), $maxLevel, $currentLevel + 1);
- if (!empty($nestedSubordinateIds)) {
- $subordinateIds = array_merge($subordinateIds, $nestedSubordinateIds);
- }
- }
- return array_unique($subordinateIds);
- }
- /**
- * 获取用户树
- * @param int $userId 用户ID
- * @return array 用户树,格式:[{name: '张三', parent: null, children: [...]}]
- */
- public function getUserTree($userId)
- {
- /** @var SharedProsperityUserDao $shareUserDao */
- $shareUserDao = app()->make(SharedProsperityUserDao::class);
- // 获取所有下级用户ID(包括自己)
- $subordinateIds = $shareUserDao->getAllSubordinateUserIds($userId, true);
- if (empty($subordinateIds)) {
- return [];
- }
- // 获取这些共富用户的基本信息(包含parent_id)
- $sharedUsers = $shareUserDao->getSharedProsperityUserEntityListByUserIdList($subordinateIds);
- if (empty($sharedUsers)) {
- return [];
- }
- // 用户身份
- $partnerLevel = [
- 0 => '用户',
- 1 => '一星合伙人',
- 2 => '二星合伙人',
- 3 => '三星合伙人',
- 4 => '钻石合伙人',
- 5 => '总裁合伙人',
- 6 => '联席主席团',
- ];
- // 获取用户昵称映射
- $userIds = array_map(function ($entity) {
- return $entity->getUserId();
- }, $sharedUsers);
- /** @var UserDao $userDao */
- $userDao = app()->make(UserDao::class);
- $userInfos = $userDao->getUserEntityListByUidList($userIds);
- $idToName = [];
- foreach ($userInfos as $userInfo) {
- $sharedUserInfo = $shareUserDao->getSharedProsperityUserEntityListByUserIdList([$userInfo->getUid()]);
- $idToName[$userInfo->getUid()] = $userInfo->getNickname() . '(' . $userInfo->account . ')(身份:' . $partnerLevel[$sharedUserInfo[0]->getPartnerLevel()] . ')' ?? ('用户' . $userInfo->getUid());
- }
- // 构建节点数组
- $nodes = [];
- foreach ($sharedUsers as $sharedUser) {
- $nodes[] = [
- 'user_id' => $sharedUser->getUserId(),
- 'parent_id' => $sharedUser->getParentId(),
- 'name' => $idToName[$sharedUser->getUserId()] ?? ('用户' . $sharedUser->getUserId()),
- ];
- }
- // 构建树,以传入的用户为根节点
- $rootNode = $this->findNode($nodes, $userId);
- if (!$rootNode) {
- return [];
- }
- $tree = [
- 'name' => $rootNode['name'],
- 'parent' => null,
- 'children' => $this->buildSharedTree($nodes, $userId)
- ];
- return [$tree];
- }
- /**
- * 递归构建共富用户树
- * @param array $nodes 节点数组,每个节点包含 user_id, parent_id, name
- * @param int $parentId 父ID
- * @return array
- */
- private function buildSharedTree($nodes, $parentId)
- {
- $branch = [];
- foreach ($nodes as $node) {
- if ($node['parent_id'] == $parentId) {
- $children = $this->buildSharedTree($nodes, $node['user_id']);
- $branch[] = [
- 'name' => $node['name'],
- 'parent' => $this->findNodeName($nodes, $parentId) ?? null,
- 'children' => $children
- ];
- }
- }
- return $branch;
- }
- /**
- * 根据user_id查找节点名称
- * @param array $nodes
- * @param int $userId
- * @return string|null
- */
- private function findNodeName($nodes, $userId)
- {
- foreach ($nodes as $node) {
- if ($node['user_id'] == $userId) {
- return $node['name'];
- }
- }
- return null;
- }
- /**
- * 根据user_id查找节点
- * @param array $nodes
- * @param int $userId
- * @return array|null
- */
- private function findNode($nodes, $userId)
- {
- foreach ($nodes as $node) {
- if ($node['user_id'] == $userId) {
- return $node;
- }
- }
- return null;
- }
- public function adminList($params)
- {
- $page = $params['page'] ?? 1;
- $where = [];
- /** @var UserDao $userDao */
- $userDao = app()->make(UserDao::class);
- // 手机号搜索
- if (isset($params['account']) && $params['account']) {
- $params['account'] = '%' . $params['account'] . '%';
- $userData = $userDao->accountLikeByUser($params['account']);
- $uids = [];
- if ($userData) {
- $uids = array_column($userData, 'uid');
- }
- $where[] = ['a.user_id', 'in', $uids];
- }
- // 昵称搜索
- if (isset($params['nickname']) && $params['nickname']) {
- $params['nickname'] = '%' . $params['nickname'] . '%';
- $userData = $userDao->nicknameLikeByUser($params['nickname']);
- $uids = [];
- if ($userData) {
- $uids = array_column($userData, 'uid');
- }
- $where[] = ['a.user_id', 'in', $uids];
- }
- // 合伙人等级搜索
- if (isset($params['partner_level']) && $params['partner_level']) {
- $where[] = ['a.partner_level', '=', $params['partner_level']];
- }
- // 共富团等级搜索
- if (isset($params['user_group']) && $params['user_group']) {
- // /** @var SharedProsperityGroupUserDao $groupUserDao */
- // $groupUserDao = app()->make(SharedProsperityGroupUserDao::class);
- // $groupUserData = $groupUserDao->getUserByLevel($params['user_group']);
- // $uids = array_column($groupUserData['data'], 'user_id');
- // $where[] = ['user_id', 'in', $uids];
- // $page = 1;
- $where[] = ['b.group_id', '=', $params['user_group']];
- }
- $list = $this->dao->adminList($where, $page);
- return $list;
- }
- /**
- * @param $userId
- * @param $level
- * @return int
- * @author 史晨
- * @date 2026/2/27 14:23
- * 更新用户等级
- */
- public function updateLevel($userId, $level, $operator, $remark)
- {
- $userInfo = $this->dao->getWhere(['user_id' => $userId]);
- if ($level == $userInfo->partner_level) {
- return '等级未发生变化';
- }
- Db::startTrans();
- try {
- // 变更等级
- $this->dao->updateByUserId($userId, ['partner_level' => $level]);
- // 记录日志
- /** @var SharedProsperityUserLevelLogDao $logDao */
- $logDao = app()->make(SharedProsperityUserLevelLogDao::class);
- $logDao->create([
- 'user_id' => $userId,
- 'old_level' => $userInfo->partner_level,
- 'new_level' => $level,
- 'operator' => $operator,
- 'remark' => $remark
- ]);
- Db::commit();
- } catch (\Exception $e) {
- Db::rollback();
- return $e->getMessage();
- }
- }
- /**
- * @param $userId
- * @param $type
- * @param $number
- * @return bool
- * @author 史晨
- * @date 2026/2/27 15:16
- * 更新用户奖励
- */
- public function updateReward($userId, $type, $number, $remark)
- {
- // 使用枚举常量代替硬编码数字
- $typeConstants = SharedProsperityRewardRecordEnum::TYPE;
- $CONSUMER_STOCKS_TYPE = $typeConstants['CONSUMER_STOCKS']['code'] ?? 1001;
- $WITHDRAWAL_LIMIT_TYPE = $typeConstants['WITHDRAWAL_LIMIT']['code'] ?? 1002;
- $PV_TYPE = $typeConstants['PV']['code'] ?? 1003;
-
- $map = [
- $CONSUMER_STOCKS_TYPE => 'consumer_stocks',
- $WITHDRAWAL_LIMIT_TYPE => 'withdrawal_limit',
- $PV_TYPE => 'pv'
- ];
- try {
- Db::startTrans();
- // 计算收支类型 (pm)
- $pm = $number >= 0 ? 1 : 0;
- $absNumber = abs($number);
- $currentTime = date('Y-m-d H:i:s');
- if (isset($map[$type])) {
- if ($type == $WITHDRAWAL_LIMIT_TYPE) {
- // 处理提现额度
- $this->handleWithdrawalLimit($userId, $number, $pm, $absNumber, $remark);
- } else {
- // 处理消费股或PV值
- $this->handleSharedProsperityReward($userId, $type, $map[$type], $number, $pm, $absNumber, $remark, $currentTime);
- }
- } else {
- // 处理佣金
- $this->handleBrokerage($userId, $number, $pm, $absNumber, $remark, $currentTime);
- }
-
- Db::commit();
- return true;
- } catch (\Exception $e) {
- Db::rollback();
- return false;
- }
- }
- /**
- * 处理提现额度更新
- * @param int $userId 用户ID
- * @param float $number 变动金额
- * @param int $pm 收支类型 (1:收入, 0:支出)
- * @param float $absNumber 变动金额绝对值
- * @param string $remark 备注
- * @return void
- */
- private function handleWithdrawalLimit($userId, $number, $pm, $absNumber, $remark)
- {
- /** @var UserDao $userDao */
- $userDao = app()->make(UserDao::class);
-
- // 更新提现额度
- $userDao->updateWithdrawalLimitByUid($userId, $number);
-
- // 获取更新后的余额
- $userData = $userDao->getWhere(['uid' => $userId]);
- $balance = $userData->withdrawal_limit;
-
- // 记录日志
- $insertData = [
- 'user_id' => $userId,
- 'pm' => $pm,
- 'number' => $absNumber,
- 'balance' => $balance,
- 'status' => 1,
- 'type_shop' => 0,
- 'take_time' => date('Y-m-d H:i:s'),
- 'remark' => $remark
- ];
-
- /** @var UserWithdrawalLimitRecordDao $withdrawalRecordDao */
- $withdrawalRecordDao = app()->make(UserWithdrawalLimitRecordDao::class);
- $withdrawalRecordDao->create($insertData);
- }
- /**
- * 处理共富体系奖励(消费股/PV值)
- * @param int $userId 用户ID
- * @param int $type 奖励类型
- * @param string $field 数据库字段名
- * @param float $number 变动金额
- * @param int $pm 收支类型 (1:收入, 0:支出)
- * @param float $absNumber 变动金额绝对值
- * @param string $remark 备注
- * @param string $currentTime 当前时间
- * @return void
- */
- private function handleSharedProsperityReward($userId, $type, $field, $number, $pm, $absNumber, $remark, $currentTime)
- {
- // 使用枚举常量
- $typeConstants = SharedProsperityRewardRecordEnum::TYPE;
- $CONSUMER_STOCKS_TYPE = $typeConstants['CONSUMER_STOCKS']['code'] ?? 1001;
- $PV_TYPE = $typeConstants['PV']['code'] ?? 1003;
-
- // 更新数据
- $this->dao->updateRewardByUserId($userId, $field, $number);
-
- // 获取更新后的余额
- $userData = $this->dao->getWhere(['user_id' => $userId]);
-
- // 根据类型确定余额字段
- if ($type == $CONSUMER_STOCKS_TYPE) {
- $balance = $userData->consumer_stocks;
- } elseif ($type == $PV_TYPE) {
- $balance = $userData->pv;
- } else {
- $balance = 0;
- }
-
- // 记录日志
- $insertData = [
- 'user_id' => $userId,
- 'type' => $type,
- 'pm' => $pm,
- 'number' => $absNumber,
- 'balance' => $balance,
- 'status' => SharedProsperityRewardRecordEnum::STATUS['VALID']['code'],
- 'type_shop' => SharedProsperityRewardRecordEnum::TYPE_SHOP['Platform']['code'],
- 'order_sn' => 0,
- 'take_time' => $currentTime,
- 'remark' => $remark,
- 'create_time' => $currentTime,
- 'update_time' => $currentTime,
- ];
-
- /** @var SharedProsperityRewardRecordDao $rewardRecordDao */
- $rewardRecordDao = app()->make(SharedProsperityRewardRecordDao::class);
- $rewardRecordDao->insertAll([$insertData]);
- }
- /**
- * 处理佣金更新
- * @param int $userId 用户ID
- * @param float $number 变动金额
- * @param int $pm 收支类型 (1:收入, 0:支出)
- * @param float $absNumber 变动金额绝对值
- * @param string $remark 备注
- * @param string $currentTime 当前时间
- * @return void
- */
- private function handleBrokerage($userId, $number, $pm, $absNumber, $remark, $currentTime)
- {
- /** @var UserDao $userDao */
- $userDao = app()->make(UserDao::class);
-
- // 更新佣金
- $userDao->updateBrokeragePriceByUid($userId, $number);
-
- // 获取更新后的余额
- $userData = $userDao->getWhere(['uid' => $userId]);
- $balance = $userData->brokerage_price;
-
- // 记录账单
- $bill = [
- 'uid' => $userId,
- 'link_id' => 0,
- 'pm' => $pm,
- 'title' => $remark,
- 'category' => 'now_money',
- 'type' => 'commission',
- 'number' => $absNumber,
- 'balance' => $balance,
- 'mark' => $remark,
- 'create_time' => $currentTime,
- 'status' => 1,
- 'commission_type' => CommonEnum::COMMISSION_TYPE['SHARED_PROSPERITY_PARTNER_COMMISSION']['code'],
- 'order_sn' => 0,
- 'tripartite' => 0,
- 'type_shop' => 0,
- 'mer_id' => 0,
- 'source' => 0,
- 'order_type' => 1,
- 'is_red_brokerage' => 0,
- 'gzc' => 3,
- 'take_time' => time(),
- 'district_id' => '',
- 'street_id' => '',
- 'month' => '',
- ];
-
- Db::name('user_bill')->insert($bill);
- }
- /**
- * 第一次促销的 身份 升级方法
- * @param SharedProsperityUserEntity $sharedProsperityUserEntity
- * @return void
- */
- public function upgradeUpperLevelsByPromotionOne(SharedProsperityUserEntity $sharedProsperityUserEntity)
- {
- // 判断当前用户 是否在共富区的消费值 > 298,如果不满足则不能升级
- /** @var StoreOrderRepository $storeOrderRepository */
- $storeOrderRepository = app()->make(StoreOrderRepository::class);
- $sumTotalPrice = $storeOrderRepository->getSumTotalPriceByUidAndMerId($sharedProsperityUserEntity->getUserId(), CommonEnum::DESIGN_MERCHANT_ID['SharedProsperity']['code']);
- if ($sumTotalPrice < 298) {
- return;
- }
- // 查询当前用户的直属下级
- $sharedProsperityUserEntityListByChild = $this->getSharedProsperityUserEntityListByParentId($sharedProsperityUserEntity->getUserId());
- // 一星合伙人数量
- $oneStarPartner = 0;
- // 二星合伙人数量
- $twoStarPartner = 0;
- foreach ($sharedProsperityUserEntityListByChild as $sharedProsperityUserEntityByChild) {
- if ($sharedProsperityUserEntityByChild->getPartnerLevel() >= 1) {
- $oneStarPartner++;
- if ($sharedProsperityUserEntityByChild->getPartnerLevel() >= 2) {
- $twoStarPartner++;
- }
- }
- }
- // 推荐 6 个 2星以上的合伙人 增加万人团身份
- if ($twoStarPartner >= 6) {
- /** @var SharedProsperityGroupUserRepository $sharedProsperityGroupUserRepository */
- $sharedProsperityGroupUserRepository = app()->make(SharedProsperityGroupUserRepository::class);
- $sharedProsperityGroupUserEntity = $sharedProsperityGroupUserRepository->getSharedProsperityGroupUserEntityByUserId($sharedProsperityUserEntity->getUserId());
- if (empty($sharedProsperityGroupUserEntity->getId())) {
- // 如果没有共富团身份 则增加共富团 万人团身份
- $sharedProsperityGroupUserRepository->createByEntity(
- SharedProsperityGroupUserEntity::newInstance()
- ->setUserId($sharedProsperityUserEntity->getUserId())
- ->setGroupId(1)
- ->setStatus(1)
- );
- }
- }
- // 推荐 6 个 1星以上的合伙人 则升级为 2 星合伙人
- if ($sharedProsperityUserEntity->getPartnerLevel() < 2 && $oneStarPartner >= 6) {
- $this->updateByEntity(
- SharedProsperityUserEntity::newInstance()
- ->setId($sharedProsperityUserEntity->getId())
- ->setPartnerLevel(2)
- );
- // 如果当前用户升级了 那要看一下他的上级 是否也需要升级
- if (!empty($sharedProsperityUserEntity->getParentId())) {
- $sharedProsperityUserEntityByParent = $this->getSharedProsperityUserEntityByUserId($sharedProsperityUserEntity->getParentId());
- if (!empty($sharedProsperityUserEntityByParent->getId()) && $sharedProsperityUserEntityByParent->getPartnerLevel() < 2) {
- $this->upgradeUpperLevelsByPromotionOne($sharedProsperityUserEntityByParent);
- }
- }
- }
- }
- }
|