UserNetwork.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. <?php
  2. namespace common\models;
  3. use common\components\ActiveRecord;
  4. use common\helpers\Cache;
  5. use common\helpers\NetPoint;
  6. use common\helpers\user\Info;
  7. use common\helpers\user\Perf;
  8. use Yii;
  9. use yii\data\Pagination;
  10. use yii\helpers\Json;
  11. /**
  12. * This is the model class for table "{{%USER_NETWORK}}".
  13. *
  14. * @property string $ID
  15. * @property string $USER_ID 会员ID
  16. * @property string $PARENT_UID 相对上级会员ID
  17. * @property int $LOCATION_TAG 网体标记
  18. * @property int $RELATIVE_LOCATION 相对上级会员区位
  19. * @property string $TOP_UID 顶端会员ID
  20. * @property string $PARENT_UIDS 所有上级ID
  21. * @property int $TOP_DEEP 距离顶端会员深度
  22. * @property int $CREATED_AT 创建时间
  23. * @property int $UPDATED_AT 更新时间
  24. */
  25. class UserNetwork extends \common\components\ActiveRecord
  26. {
  27. /**
  28. * @inheritdoc
  29. */
  30. public static function tableName()
  31. {
  32. return '{{%USER_NETWORK_NEW}}';
  33. }
  34. /**
  35. * @inheritdoc
  36. */
  37. public function rules()
  38. {
  39. return [
  40. [['USER_ID', 'PARENT_UID', 'LOCATION', 'TOP_UID', 'TOP_DEEP', 'CREATED_AT'], 'required'],
  41. [['TOP_DEEP', 'PERIOD_NUM', 'RELATIVE_LOCATION', 'CREATED_AT', 'UPDATED_AT'], 'integer'],
  42. [['ID', 'USER_ID', 'PARENT_UID', 'TOP_UID'], 'string', 'max' => 32],
  43. [['ID'], 'unique'],
  44. ];
  45. }
  46. /**
  47. * @inheritdoc
  48. */
  49. public function attributeLabels()
  50. {
  51. return [
  52. 'ID' => 'ID',
  53. 'USER_ID' => '会员ID',
  54. 'PARENT_UID' => '相对上级会员ID',
  55. 'LOCATION_TAG' => '网体标记',
  56. 'RELATIVE_LOCATION' => '相对父级的区位',
  57. 'TOP_UID' => '顶端会员ID',
  58. 'TOP_DEEP' => '距离顶端会员深度',
  59. 'PARENT_UIDS' => '所有上级ID',
  60. 'CREATED_AT' => '创建时间',
  61. 'UPDATED_AT' => '更新时间',
  62. ];
  63. }
  64. /**
  65. * 获取一层下级数量
  66. * @param $userId
  67. * @return int|string
  68. */
  69. public static function firstFloorChildNum($userId){
  70. return intval(UserInfo::find()->where('CON_UID=:CON_UID AND DELETED=0', [':CON_UID'=>$userId])->count());
  71. }
  72. /**
  73. * 分页获取上级会员
  74. * @param $userId
  75. * @param $offset
  76. * @param $limit
  77. * @param string $orderBy
  78. * @param bool $isSlaves
  79. * @param string $db
  80. * @return array|\yii\db\ActiveRecord[]
  81. */
  82. public static function getParentsWithOffset($userId, $offset, $limit, $orderBy='DESC', $isSlaves = false, $db = 'db'){
  83. $userNetInfo = static::find($isSlaves, $db)->select(['TOP_DEEP', 'PARENT_UIDS', 'LOCATION_TAG'])->where('USER_ID=:USER_ID', ['USER_ID'=>$userId])->asArray()->one();
  84. if( !$userNetInfo ) return [];
  85. $parentUidsStr = $userNetInfo['PARENT_UIDS'];
  86. if( !$parentUidsStr ) return [];
  87. $parentUidsArr = explode(',', $parentUidsStr);
  88. unset($parentUidsStr);
  89. if( $orderBy === 'DESC' ) {
  90. $parentUidsArr = array_reverse($parentUidsArr);
  91. }
  92. if( !$parentUidsArr ) return [];
  93. $pageParentUids = array_slice($parentUidsArr, $offset, $limit);
  94. unset($parentUidsArr);
  95. $parentList = [];
  96. foreach ($pageParentUids as $parentUid) {
  97. $parentNetInfo = static::find($isSlaves, $db)->select(['TOP_DEEP', 'LOCATION_TAG'])->where('USER_ID=:USER_ID', ['USER_ID'=>$parentUid])->asArray()->one();
  98. $parentList[] = [
  99. 'USER_ID' => $userId,
  100. 'TOP_DEEP' => $userNetInfo['TOP_DEEP'],
  101. 'PARENT_UID' => $parentUid,
  102. 'PARENT_DEEP' => $parentNetInfo['TOP_DEEP'],
  103. // 'LOCATION_TAG' => $userNetInfo['LOCATION_TAG'],
  104. // 'PARENT_LOCATION_TAG' => $parentNetInfo['LOCATION_TAG'],
  105. 'LOCATION' => substr($userNetInfo['LOCATION_TAG'], strlen($parentNetInfo['LOCATION_TAG']), 1),
  106. ];
  107. unset($parentUid, $parentNetInfo);
  108. }
  109. unset($pageParentUids, $userNetInfo);
  110. return $parentList;
  111. }
  112. /**
  113. * 分页获取上级会员结算库
  114. * @param $userId
  115. * @param $callbackFunc
  116. * @param $limit
  117. * @param int $offset
  118. * @param string $orderBy
  119. */
  120. public static function getParentsWithOffsetFromDbCalc($userId, $callbackFunc, $limit, $offset = 0, $orderBy='DESC'){
  121. $allData = self::getParentsWithOffset($userId, $offset, $limit, $orderBy, false, 'dbCalc');
  122. if($allData){
  123. foreach($allData as $data){
  124. $callbackFunc($data);
  125. unset($data);
  126. }
  127. unset($allData);
  128. self::getParentsWithOffsetFromDbCalc($userId, $callbackFunc, $limit, $offset + $limit);
  129. }
  130. }
  131. /**
  132. * 获取上一级父级的会员信息
  133. * @param $userId
  134. * @return array|null
  135. */
  136. public static function getFirstParentUserInfo($userId){
  137. $oneUserInfo = UserInfo::findOneAsArray(['USER_ID'=>$userId]);
  138. if($oneUserInfo['CON_UID']){
  139. return UserInfo::findOneAsArray(['USER_ID'=>$oneUserInfo['CON_UID']]);
  140. } else {
  141. return null;
  142. }
  143. }
  144. /**
  145. * 获取指定深度的子会员
  146. * @param $userId
  147. * @param $deep
  148. * @param string $orderBy
  149. * @return array
  150. */
  151. public static function getChildrenWithDeep($userId, $deep, $orderBy='TOP_DEEP ASC'){
  152. $userNetInfo = static::find()->select(['LOCATION_TAG', 'TOP_DEEP'])->where('USER_ID=:USER_ID', ['USER_ID'=>$userId])->asArray()->one();
  153. $childrenNetInfo = static::find()->select(['USER_ID', 'LOCATION_TAG', 'TOP_DEEP'])->where('LOCATION_TAG LIKE :LOCATION_TAG AND TOP_DEEP<=:TOP_DEEP', ['LOCATION_TAG'=>$userNetInfo['LOCATION_TAG'] . '%', 'TOP_DEEP'=>$userNetInfo['TOP_DEEP'] + $deep])->orderBy($orderBy)->asArray()->all();
  154. foreach ($childrenNetInfo as $key => $childNetInfo) {
  155. $childrenNetInfo[$key]['LOCATION'] = substr($childNetInfo['LOCATION_TAG'], strlen($userNetInfo['LOCATION_TAG']), 1);
  156. unset($key, $childNetInfo);
  157. }
  158. unset($userNetInfo);
  159. return $childrenNetInfo;
  160. }
  161. /**
  162. * 获取下一层会员的接点信息
  163. * @param $userId
  164. * @return array|\yii\db\ActiveRecord[]
  165. */
  166. public static function getFirstFloorChildren($userId) {
  167. $childrenNetInfo = static::find()->select(['USER_ID', 'RELATIVE_LOCATION', 'LOCATION_TAG', 'TOP_DEEP'])->where('PARENT_UID=:PARENT_UID', ['PARENT_UID'=>$userId])->asArray()->all();
  168. unset($userNetInfo);
  169. return $childrenNetInfo;
  170. }
  171. /**
  172. * 查看所传父级节点会员是不是所传会员的父级
  173. * @param $userId
  174. * @param $parentUserId
  175. * @param null $periodNum
  176. * @return bool
  177. * @throws \yii\db\Exception
  178. */
  179. public static function isParentUser($userId, $parentUserId, $periodNum = null){
  180. $table = self::getTableNameFromPeriod($periodNum);
  181. $db = $table['db'];
  182. $tableName = $table['tableName'];
  183. $data = $db->createCommand("SELECT PARENT_UIDS FROM {$tableName} WHERE USER_ID=:USER_ID")->bindValues([':USER_ID'=>$userId])->queryOne();
  184. if( !$data ) {
  185. unset($table, $db, $tableName, $data);
  186. return false;
  187. }
  188. $parentListArr = explode(',', $data['PARENT_UIDS']);
  189. unset($table, $db, $tableName, $data);
  190. $existStatus = in_array($parentUserId, $parentListArr);
  191. unset($parentListArr);
  192. return $existStatus;
  193. }
  194. /**
  195. * 获取会员相较于父级的区位
  196. * @param $userId
  197. * @param $parentUserId
  198. * @param $periodNum
  199. * @return mixed|null
  200. */
  201. public static function getLocation($userId, $parentUserId, $periodNum = null){
  202. $table = self::getTableNameFromPeriod($periodNum);
  203. $db = $table['db'];
  204. $tableName = $table['tableName'];
  205. $userNetInfo = $db->createCommand("SELECT LOCATION_TAG FROM $tableName WHERE USER_ID=:USER_ID")->bindValues([':USER_ID'=>$userId])->queryOne();
  206. if( !$userNetInfo || !isset($userNetInfo['LOCATION_TAG']) ) return 0;
  207. $parentNetInfo = $db->createCommand("SELECT LOCATION_TAG FROM $tableName WHERE USER_ID=:USER_ID")->bindValues([':USER_ID'=>$userId])->queryOne();
  208. if( !$parentNetInfo || !isset($parentNetInfo['LOCATION_TAG']) ) return 0;
  209. $location = substr($userNetInfo['LOCATION_TAG'], strlen($parentNetInfo['LOCATION_TAG']), 1);
  210. return $location ? $location : 0;
  211. }
  212. /**
  213. * 获取子会员节点带着总深度和循环的子节点层级关系
  214. * @param $userId
  215. * @param $deep
  216. * @param int $loopedDeep
  217. * @param null $periodNum
  218. * @return mixed
  219. * @throws \yii\base\Exception
  220. * @throws \yii\db\Exception
  221. */
  222. public static function getChildrenWithDeepAndLayer($userId, $deep, $loopedDeep = 1, $periodNum=null){
  223. $allData = self::getChildrenFromPeriod($userId, $periodNum);
  224. if($allData){
  225. $decLevelConfig = Cache::getDecLevelConfig();
  226. $empLevelConfig = Cache::getEmpLevelConfig();
  227. foreach($allData as $key=>$data){
  228. // 获取用户的基本信息
  229. $baseInfo = Info::baseInfo($data['USER_ID'], $periodNum);
  230. $allData[$key] = array_merge($data, [
  231. 'USER_NAME' => $baseInfo['USER_NAME'],
  232. 'TOP_NETWORK_DEEP' => $data['TOP_DEEP'],
  233. 'REAL_NAME' => $baseInfo['REAL_NAME'],
  234. 'DEC_LV_NAME' => $decLevelConfig[$baseInfo['DEC_LV']]['LEVEL_NAME'],
  235. 'EMP_LV_NAME' => isset($empLevelConfig[$baseInfo['EMP_LV']])?$empLevelConfig[$baseInfo['EMP_LV']]['LEVEL_NAME']:'',
  236. // 'MOBILE' => $baseInfo['MOBILE'],
  237. 'PERIOD_AT' => $baseInfo['PERIOD_AT'],
  238. ]);
  239. // 获取字节点数量
  240. $childNum = self::firstFloorChildNumFromPeriod($data['USER_ID'], $periodNum);
  241. if($childNum > 0 && $loopedDeep < $deep){
  242. $child = self::getChildrenWithDeepAndLayer($data['USER_ID'], $deep, $loopedDeep + 1, $periodNum);
  243. $leaf = false;
  244. $icon = 'el-icon-user-solid';
  245. }
  246. elseif($childNum > 0){
  247. $child = null;
  248. $leaf = false;
  249. $icon = 'el-icon-user-solid';
  250. }
  251. else {
  252. $child = null;
  253. $leaf = true;
  254. $icon = 'el-icon-user';
  255. }
  256. $allData[$key]['children'] = $child;
  257. $allData[$key]['leaf'] = $leaf;
  258. $allData[$key]['icon'] = $icon;
  259. $allData[$key]['isExpanded'] = false;
  260. $allData[$key]['displayNone'] = 'display-none';
  261. }
  262. }
  263. return $allData;
  264. }
  265. /**
  266. * 通过期数获取应该查询哪个表和库
  267. * @param $periodNum
  268. * @return array
  269. */
  270. public static function getTableNameFromPeriod($periodNum = null){
  271. $db = self::getDb();
  272. $tableName = self::tableName();
  273. // if($periodNum !== null){
  274. // // 获取当前期数
  275. // $period = Period::instance();
  276. // $nowPeriodNum = $period->getNowPeriodNum();
  277. // if($nowPeriodNum != $periodNum){
  278. // // 从备份库里找到期数对应的网络
  279. // if(ActiveRecord::isExistsTable('{{%USER_NETWORK_'.$periodNum.'}}', 'dbNetPoint')){
  280. // $db = Yii::$app->dbNetPoint;
  281. // $tableName = '{{%USER_NETWORK_'.$periodNum.'}}';
  282. // }
  283. // }
  284. // }
  285. return [
  286. 'db' => $db,
  287. 'tableName' => $tableName,
  288. ];
  289. }
  290. /**
  291. * 获取指定深度的子会员从指定的期数中
  292. * @param $userId
  293. * @param $periodNum
  294. * @return array|\yii\db\DataReader
  295. * @throws \yii\db\Exception
  296. */
  297. public static function getChildrenFromPeriod($userId, $periodNum=null){
  298. $table = self::getTableNameFromPeriod($periodNum);
  299. $db = $table['db'];
  300. $tableName = $table['tableName'];
  301. return $db->createCommand("SELECT USER_ID,TOP_DEEP,RELATIVE_LOCATION FROM {$tableName} WHERE PARENT_UID=:PARENT_UID")->bindValues([':PARENT_UID'=>$userId])->queryAll();
  302. }
  303. /**
  304. * 获取指定层数的这一层的会员以分页的方式
  305. * @param $userId
  306. * @param $deep
  307. * @param null $periodNum
  308. * @param array $params
  309. * @return array
  310. */
  311. public static function getChildrenInDeepFromPeriodWithPage($userId, $deep, $periodNum=null, $params=[]){
  312. $pageSize = method_exists(\Yii::$app->request,'get')?\Yii::$app->request->get('pageSize', \Yii::$app->params['pageSize']):\Yii::$app->params['pageSize'];
  313. if(isset($params['pageSize'])) $pageSize=$params['pageSize'];
  314. $page = null;
  315. if( isset($params['page']) ) $page=$params['page'];
  316. $orderBy = 'TOP_DEEP ASC, ID ASC';
  317. if( isset($params['orderBy']) ) $orderBy = $params['orderBy'];
  318. $table = self::getTableNameFromPeriod($periodNum);
  319. $db = $table['db'];
  320. $tableName = $table['tableName'];
  321. $userNetInfo = $db->createCommand("SELECT LOCATION_TAG,TOP_DEEP FROM {$tableName} WHERE USER_ID=:USER_ID")->bindValues([':USER_ID'=>$userId])->queryOne();
  322. $userDeep = $userNetInfo['TOP_DEEP'];
  323. $userLocationTag = $userNetInfo['LOCATION_TAG'];
  324. $totalCountSql = "SELECT COUNT(ID) AS TOTAL_COUNT FROM {$tableName} WHERE LOCATION_TAG LIKE :LOCATION_TAG AND TOP_DEEP<=:TOP_DEEP AND INSTR(`PARENT_UIDS`,'{$userId}')>0 ORDER BY {$orderBy}";
  325. $totalCount = $db->createCommand($totalCountSql)->bindValues([':LOCATION_TAG'=>$userLocationTag . '%', ':TOP_DEEP'=>$userDeep + $deep])->queryOne();
  326. $count = $totalCount['TOTAL_COUNT'];
  327. $pagination = new Pagination(['totalCount' => $count]);
  328. $pagination->setPageSize($pageSize);
  329. if( $page !== null ) {
  330. $pagination->setPage($page);
  331. }
  332. $offset = $pagination->offset;
  333. $limit = $pagination->limit;
  334. // $end = $offset + $limit;
  335. $listSql = "SELECT * FROM $tableName WHERE LOCATION_TAG LIKE :LOCATION_TAG AND TOP_DEEP<=:TOP_DEEP AND INSTR(`PARENT_UIDS`,'{$userId}')>0 ORDER BY {$orderBy} LIMIT {$limit} OFFSET {$offset}";
  336. $lists = $db->createCommand($listSql)->bindValues([':LOCATION_TAG'=>$userLocationTag . '%', ':TOP_DEEP'=>$userDeep + $deep])->queryAll();
  337. return [
  338. 'list' => $lists ? $lists : [],
  339. 'pagination' => $pagination,
  340. 'currentPage'=>$pagination->page,
  341. 'totalPages'=>$pagination->pageCount,
  342. 'totalCount' => $pagination->totalCount,
  343. 'pageSize' => $pagination->pageSize,
  344. ];
  345. }
  346. /**
  347. * 获取所有的上级会员带着分页和期数
  348. * @param $userId
  349. * @param null $periodNum
  350. * @param null $deep
  351. * @return array
  352. */
  353. public static function getAllParentFromPeriodWithPage($userId, $periodNum=null, $deep=null){
  354. $pageSize = method_exists(\Yii::$app->request,'get')?\Yii::$app->request->get('pageSize', \Yii::$app->params['pageSize']):\Yii::$app->params['pageSize'];
  355. $table = self::getTableNameFromPeriod($periodNum);
  356. $db = $table['db'];
  357. $tableName = $table['tableName'];
  358. $sql = "SELECT * FROM {$tableName} WHERE USER_ID=:USER_ID";
  359. $oneData = $db->createCommand($sql)->bindValues([':USER_ID'=>$userId])->queryOne();
  360. $userDeep = $oneData['TOP_DEEP'];
  361. $parentUidsStr = $oneData['PARENT_UIDS'] ?? "";
  362. if( !$parentUidsStr ) return [];
  363. $parentUidsArr = explode(',', $parentUidsStr);
  364. $parentUidsFlip = array_reverse($parentUidsArr);
  365. if ($deep != null) {
  366. $parentUidsFlip = array_slice($parentUidsFlip, 0, $deep);
  367. }
  368. $count = count($parentUidsFlip);
  369. $pagination = new Pagination(['totalCount' => $count]);
  370. $pagination->setPageSize($pageSize);
  371. $offset = $pagination->offset;
  372. $limit = $pagination->limit;
  373. $parentUidList = array_slice($parentUidsFlip, $offset, $limit);
  374. $lists = [];
  375. foreach ($parentUidList as $parentUid) {
  376. $sql = "SELECT * FROM {$tableName} WHERE USER_ID=:USER_ID";
  377. $data = $db->createCommand($sql)->bindValues([':USER_ID' => $parentUid])->queryOne();
  378. if( !$data ) continue;
  379. $data['LOCATION'] = substr($oneData['LOCATION_TAG'], strlen($data['LOCATION_TAG']), 1);
  380. $lists[] = $data;
  381. }
  382. return [
  383. 'list' => $lists ? $lists : [],
  384. 'pagination' => $pagination,
  385. 'currentPage' => $pagination->page,
  386. 'totalPages' => $pagination->pageCount,
  387. 'totalCount' => $pagination->totalCount,
  388. 'pageSize' => $pagination->pageSize,
  389. 'listTopDeep' => $userDeep,
  390. ];
  391. }
  392. /**
  393. * 获取一层下级数量从期数
  394. * @param $userId
  395. * @param null $periodNum
  396. * @return int
  397. */
  398. public static function firstFloorChildNumFromPeriod($userId, $periodNum=null){
  399. $table = self::getTableNameFromPeriod($periodNum);
  400. $db = $table['db'];
  401. $tableName = $table['tableName'];
  402. $count = $db->createCommand("SELECT COUNT(ID) AS ID_COUNT FROM {$tableName} WHERE PARENT_UID=:PARENT_UID")->bindValues([':PARENT_UID'=>$userId])->queryOne();
  403. return intval($count['ID_COUNT']);
  404. }
  405. /**
  406. * 从缓存中获取会员的全部父级(主要用于结算时的处理,能够提高效率不去查库)
  407. * @param $userId
  408. * @return array|mixed
  409. */
  410. public static function getAllParentsFromRedis($userId){
  411. $key = Cache::USER_NETWORK_PARENTS;
  412. $data = Yii::$app->redis->hget($key, $userId);
  413. if(!$data){
  414. $data = [];
  415. self::getParentsWithOffsetFromDbCalc($userId, function($oneData) use(&$data){
  416. $data[] = $oneData;
  417. }, 100);
  418. $data = Json::encode($data);
  419. Yii::$app->redis->hset($key, $userId, $data);
  420. }
  421. return $data ? Json::decode($data) : [];
  422. }
  423. /**
  424. * 判断在某个区位是否存在会员
  425. * @param $userId
  426. * @param $location
  427. * @return bool
  428. */
  429. public static function issetUserInLocation($userId, $location){
  430. $childrenNetList = UserNetwork::find()->select(['LOCATION_TAG'])->where('PARENT_UID=:PARENT_UID', [':PARENT_UID' => $userId])->asArray()->all();
  431. foreach ($childrenNetList as $everyData) {
  432. //取最后一位数
  433. $everyLocation = substr($everyData['LOCATION_TAG'], -1);
  434. if( $everyLocation == $location ) return true;
  435. }
  436. return false;
  437. }
  438. }