UserNetwork.php 19 KB

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