User.php 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002
  1. <?php
  2. namespace app\models\user;
  3. use app\models\auction\Auction;
  4. use app\models\auction\AuctionBooking;
  5. use app\models\auction\AuctionOrder;
  6. use app\models\auction\AuctionPush;
  7. use app\models\auction\AuctionReward;
  8. use app\models\store\StoreOrder;
  9. use app\models\store\StoreProduct;
  10. use crmeb\services\SystemConfigService;
  11. use think\db\exception\DataNotFoundException;
  12. use think\db\exception\DbException;
  13. use think\db\exception\ModelNotFoundException;
  14. use think\Exception;
  15. use think\facade\Session;
  16. use crmeb\traits\ModelTrait;
  17. use crmeb\basic\BaseModel;
  18. use crmeb\traits\JwtAuthModelTrait;
  19. /**
  20. * TODO 用户Model
  21. * Class User
  22. * @package app\models\user
  23. */
  24. class User extends BaseModel
  25. {
  26. use JwtAuthModelTrait;
  27. use ModelTrait;
  28. protected $pk = 'uid';
  29. protected $name = 'user';
  30. protected $insert = ['add_time', 'add_ip', 'last_time', 'last_ip'];
  31. protected $hidden = [
  32. 'add_ip', 'add_time', 'account', 'clean_time', 'last_ip', 'last_time', 'pwd', 'status', 'mark', 'pwd'
  33. ];
  34. protected function setAddTimeAttr($value)
  35. {
  36. return time();
  37. }
  38. protected function setAddIpAttr($value)
  39. {
  40. return app('request')->ip();
  41. }
  42. protected function setLastTimeAttr($value)
  43. {
  44. return time();
  45. }
  46. protected function setLastIpAttr($value)
  47. {
  48. return app('request')->ip();
  49. }
  50. /**
  51. * @param $wechatUser
  52. * @param int $spread_uid
  53. * @return bool
  54. * @throws DataNotFoundException
  55. * @throws DbException
  56. * @throws ModelNotFoundException
  57. */
  58. public static function setWechatUser($wechatUser, $spread_uid = 0)
  59. {
  60. $res = self::create([
  61. 'account' => 'wx' . $wechatUser['uid'] . time(),
  62. 'pwd' => md5(123456),
  63. 'nickname' => $wechatUser['nickname'] ?: '',
  64. 'avatar' => $wechatUser['headimgurl'] ?: '',
  65. 'add_time' => time(),
  66. 'add_ip' => app('request')->ip(),
  67. 'last_time' => time(),
  68. 'last_ip' => app('request')->ip(),
  69. 'uid' => $wechatUser['uid'],
  70. 'user_type' => 'wechat'
  71. ]);
  72. return $res && UserSpread::setSpread($wechatUser['uid'], $spread_uid);
  73. }
  74. /**
  75. * TODO 获取会员是否被清除过的时间
  76. * @param $uid
  77. * @return int|mixed
  78. * @throws DataNotFoundException
  79. * @throws ModelNotFoundException
  80. * @throws DbException
  81. */
  82. public static function getCleanTime($uid)
  83. {
  84. $user = self::where('uid', $uid)->field(['add_time', 'clean_time'])->find();
  85. if (!$user) return 0;
  86. return $user['clean_time'] ? $user['clean_time'] : $user['add_time'];
  87. }
  88. /**
  89. * 更新用户信息
  90. * @param array $wechatUser 用户信息
  91. * @param int $uid 用户uid
  92. * @return bool|void
  93. * @throws DataNotFoundException
  94. * @throws ModelNotFoundException
  95. * @throws DbException
  96. */
  97. public static function updateWechatUser($wechatUser, $uid)
  98. {
  99. $userInfo = self::where('uid', $uid)->find();
  100. if (!$userInfo) return;
  101. //增加成为分销权限
  102. if (!$userInfo->is_promoter) {
  103. $price = StoreOrder::where(['paid' => 1, 'refund_status' => 0, 'uid' => $uid])->sum('pay_price');
  104. $status = is_brokerage_statu($price);
  105. } else {
  106. $status = false;
  107. }
  108. if ($userInfo->spread_uid) {
  109. return self::edit([
  110. 'nickname' => $wechatUser['nickname'] ?: '',
  111. 'avatar' => $wechatUser['headimgurl'] ?: '',
  112. 'is_promoter' => $status ? 1 : $userInfo->is_promoter,
  113. 'login_type' => isset($wechatUser['login_type']) ? $wechatUser['login_type'] : $userInfo->login_type,
  114. ], $uid, 'uid');
  115. } else {
  116. $data = [
  117. 'nickname' => $wechatUser['nickname'] ?: '',
  118. 'avatar' => $wechatUser['headimgurl'] ?: '',
  119. 'is_promoter' => $status ? 1 : $userInfo->is_promoter,
  120. 'login_type' => isset($wechatUser['login_type']) ? $wechatUser['login_type'] : $userInfo->login_type,
  121. // 'spread_uid' => 0,
  122. // 'spread_time' => 0,
  123. 'last_time' => time(),
  124. 'last_ip' => request()->ip(),
  125. ];
  126. //TODO 获取后台分销类型
  127. // $storeBrokerageStatus = sys_config('store_brokerage_statu');
  128. // $storeBrokerageStatus = $storeBrokerageStatus ? $storeBrokerageStatus : 1;
  129. // if (isset($wechatUser['code']) && $wechatUser['code'] && $wechatUser['code'] != $uid && $uid != self::where('uid', $wechatUser['code'])->value('spread_uid')) {
  130. // if ($storeBrokerageStatus == 1) {
  131. // $spreadCount = self::where('uid', $wechatUser['code'])->count();
  132. // if ($spreadCount) {
  133. // $spreadInfo = self::where('uid', $wechatUser['code'])->find();
  134. // if ($spreadInfo->is_promoter) {
  135. // //TODO 只有扫码才可以获得推广权限
  136. //// if(isset($wechatUser['isPromoter'])) $data['is_promoter'] = $wechatUser['isPromoter'] ? 1 : 0;
  137. // }
  138. // }
  139. // }
  140. // $data['spread_uid'] = $wechatUser['code'];
  141. // $data['spread_time'] = time();
  142. // }
  143. return self::edit($data, $uid, 'uid') && UserSpread::setSpread($uid, $wechatUser['code'] ?? 0);
  144. }
  145. }
  146. /**
  147. * 设置推广关系
  148. * @param $spread
  149. * @param $uid
  150. * @return bool
  151. * @throws DataNotFoundException
  152. * @throws ModelNotFoundException
  153. * @throws DbException
  154. */
  155. public static function setSpread($spread, $uid)
  156. {
  157. return UserSpread::setSpread($uid, $spread);
  158. //当前用户信息
  159. // $userInfo = self::where('uid', $uid)->find();
  160. // if (!$userInfo) return true;
  161. // //当前用户有上级直接返回
  162. // if ($userInfo->spread_uid) return true;
  163. // //没有推广编号直接返回
  164. // if (!$spread) return true;
  165. // if ($spread == $uid) return true;
  166. // if ($uid == self::where('uid', $spread)->value('spread_uid')) return true;
  167. // //TODO 获取后台分销类型
  168. // $storeBrokerageStatus = sys_config('store_brokerage_statu');
  169. // $storeBrokerageStatus = $storeBrokerageStatus ? $storeBrokerageStatus : 1;
  170. // if ($storeBrokerageStatus == 1) {
  171. // $spreadCount = self::where('uid', $spread)->count();
  172. // if ($spreadCount) {
  173. // $spreadInfo = self::where('uid', $spread)->find();
  174. // if ($spreadInfo->is_promoter) {
  175. // //TODO 只有扫码才可以获得推广权限
  176. //// if(isset($wechatUser['isPromoter'])) $data['is_promoter'] = $wechatUser['isPromoter'] ? 1 : 0;
  177. // }
  178. // }
  179. // }
  180. // $data['spread_uid'] = $spread;
  181. // $data['spread_time'] = time();
  182. // return self::edit($data, $uid, 'uid');
  183. }
  184. /**
  185. * 小程序用户添加
  186. * @param $routineUser
  187. * @param int $spread_uid
  188. * @return object
  189. * @throws DataNotFoundException
  190. * @throws DbException
  191. * @throws ModelNotFoundException
  192. */
  193. public static function setRoutineUser($routineUser, $spread_uid = 0)
  194. {
  195. self::beginTrans();
  196. $res1 = true;
  197. if ($spread_uid) $res1 = self::where('uid', $spread_uid)->inc('spread_count', 1)->update();
  198. // $storeBrokerageStatu = sys_config('store_brokerage_statu') ? : 1;//获取后台分销类型
  199. $res2 = self::create([
  200. 'account' => 'rt' . $routineUser['uid'] . time(),
  201. 'pwd' => md5(123456),
  202. 'nickname' => $routineUser['nickname'] ?: '',
  203. 'avatar' => $routineUser['headimgurl'] ?: '',
  204. // 'spread_uid' => $spread_uid,
  205. // 'is_promoter'=>$spread_uid || $storeBrokerageStatu != 1 ? 1: 0,
  206. // 'spread_time' => $spread_uid ? time() : 0,
  207. 'uid' => $routineUser['uid'],
  208. 'add_time' => $routineUser['add_time'],
  209. 'add_ip' => request()->ip(),
  210. 'last_time' => time(),
  211. 'last_ip' => request()->ip(),
  212. 'user_type' => $routineUser['user_type']
  213. ]);
  214. $res = $res1 && $res2 && UserSpread::setSpread($routineUser['uid'], $spread_uid);
  215. self::checkTrans($res);
  216. return $res2;
  217. }
  218. /**
  219. * 获得当前登陆用户UID
  220. * @return int $uid
  221. */
  222. public static function getActiveUid()
  223. {
  224. $uid = null;
  225. $uid = Session::get('LoginUid');
  226. if ($uid) return $uid;
  227. else return 0;
  228. }
  229. /**
  230. * TODO 查询当前用户信息
  231. * @param $uid $uid 用户编号
  232. * @param string $field $field 查询的字段
  233. * @return array
  234. * @throws DataNotFoundException
  235. * @throws ModelNotFoundException
  236. * @throws DbException
  237. */
  238. public static function getUserInfo($uid, $field = '')
  239. {
  240. if (strlen(trim($field))) $userInfo = self::where('uid', $uid)->field($field)->find();
  241. else $userInfo = self::where('uid', $uid)->find();
  242. if (!$userInfo) return [];
  243. return $userInfo->toArray();
  244. }
  245. /**
  246. * 判断当前用户是否推广员
  247. * @param int $uid
  248. * @return bool
  249. */
  250. public static function isUserSpread($uid = 0)
  251. {
  252. if (!$uid) return false;
  253. $status = (int)sys_config('store_brokerage_statu');
  254. $isPromoter = true;
  255. if ($status == 1) $isPromoter = self::where('uid', $uid)->value('is_promoter');
  256. if ($isPromoter) return true;
  257. else return false;
  258. }
  259. /**
  260. * TODO 一级返佣
  261. * @param $orderInfo
  262. * @return bool
  263. * @throws DataNotFoundException
  264. * @throws ModelNotFoundException
  265. * @throws DbException
  266. */
  267. public static function backOrderBrokerage($orderInfo, bool $open = true)
  268. {
  269. //TODO 营销产品不返佣金
  270. if (isset($orderInfo['combination_id']) && $orderInfo['combination_id']) return true;
  271. if (isset($orderInfo['seckill_id']) && $orderInfo['seckill_id']) return true;
  272. if (isset($orderInfo['bargain_id']) && $orderInfo['bargain_id']) return true;
  273. $userInfo = User::getUserInfo($orderInfo['uid']);
  274. //TODO 当前用户不存在 没有上级 或者 当用用户上级时自己 直接返回
  275. if (!$userInfo || !$userInfo['spread_uid'] || $userInfo['spread_uid'] == $orderInfo['uid']) return true;
  276. if (!User::be(['uid' => $userInfo['spread_uid'], 'is_promoter' => 1])) return self::backOrderBrokerageTwo($orderInfo, $open);
  277. $cartId = is_string($orderInfo['cart_id']) ? json_decode($orderInfo['cart_id'], true) : $orderInfo['cart_id'];
  278. list($realBrokeragePrice, $virtualBrokeragePrice) = StoreProduct::getProductBrokerage($cartId);
  279. //TODO 返佣金额小于等于0 直接返回不返佣金
  280. if ($realBrokeragePrice <= 0 && $virtualBrokeragePrice <= 0) return true;
  281. //TODO 获取上级推广员信息
  282. // $open && self::beginTrans();
  283. $res = true;
  284. if ($virtualBrokeragePrice > 0) {
  285. $spreadUserInfo = User::getUserInfo($userInfo['spread_uid']);
  286. //TODO 上级推广员返佣之后的金额
  287. $balance = bcadd($spreadUserInfo['brokerage_price'], $virtualBrokeragePrice, 2);
  288. $mark = $userInfo['nickname'] . '成功消费[虚拟产品]' . floatval($orderInfo['pay_price']) . '元,奖励推广佣金' . floatval($virtualBrokeragePrice);
  289. //TODO 添加推广记录
  290. $res1 = UserBill::income('获得推广佣金', $userInfo['spread_uid'], 'now_money', 'brokerage', $virtualBrokeragePrice, $orderInfo['id'], $balance, $mark);
  291. //TODO 添加用户余额
  292. $res2 = self::bcInc($userInfo['spread_uid'], 'brokerage_price', $virtualBrokeragePrice, 'uid');
  293. //TODO 一级返佣成功 跳转二级返佣
  294. $res = $res1 && $res2;
  295. }
  296. if ($realBrokeragePrice > 0) {
  297. $spreadUserInfo = User::getUserInfo($userInfo['spread_uid']);
  298. //TODO 上级推广员返佣之后的金额
  299. $mark = $userInfo['nickname'] . '成功消费[实体产品]' . floatval($orderInfo['pay_price']) . '元,奖励推广佣金' . floatval($realBrokeragePrice);
  300. //TODO 添加推广记录
  301. $res = UserBill::income('获得推广佣金', $userInfo['spread_uid'], 'now_money', 'brokerage', $realBrokeragePrice, $orderInfo['id'], $spreadUserInfo['brokerage_price'], $mark, 0);
  302. }
  303. $res = $res && self::backOrderBrokerageTwo($orderInfo);
  304. // $open && self::checkTrans($res);
  305. return $res;
  306. }
  307. /**
  308. * TODO 二级推广
  309. * @param $orderInfo
  310. * @return bool
  311. * @throws DataNotFoundException
  312. * @throws ModelNotFoundException
  313. * @throws DbException
  314. */
  315. public static function backOrderBrokerageTwo($orderInfo, bool $open = true)
  316. {
  317. //TODO 获取购买商品的用户
  318. $userInfo = User::getUserInfo($orderInfo['uid']);
  319. //TODO 获取上推广人
  320. $userInfoTwo = User::getUserInfo($userInfo['spread_uid']);
  321. //TODO 上推广人不存在 或者 上推广人没有上级 或者 当用用户上上级时自己 直接返回
  322. if (!$userInfoTwo || !$userInfoTwo['spread_uid'] || $userInfoTwo['spread_uid'] == $orderInfo['uid']) return true;
  323. //TODO 获取后台分销类型 1 指定分销 2 人人分销
  324. if (!User::be(['uid' => $userInfoTwo['spread_uid'], 'is_promoter' => 1])) return true;
  325. $cartId = is_string($orderInfo['cart_id']) ? json_decode($orderInfo['cart_id'], true) : $orderInfo['cart_id'];
  326. list($realBrokeragePrice, $virtualBrokeragePrice) = StoreProduct::getProductBrokerage($cartId, false);
  327. //TODO 返佣金额小于等于0 直接返回不返佣金
  328. if ($realBrokeragePrice <= 0 && $virtualBrokeragePrice <= 0) return true;
  329. // $open && self::beginTrans();
  330. $res = true;
  331. if ($virtualBrokeragePrice > 0) {
  332. $spreadUserInfoTwo = User::getUserInfo($userInfoTwo['spread_uid']);
  333. //TODO 上级推广员返佣之后的金额
  334. $balance = bcadd($spreadUserInfoTwo['brokerage_price'], $virtualBrokeragePrice, 2);
  335. $mark = '二级推广人' . $userInfo['nickname'] . '成功消费[虚拟产品]' . floatval($orderInfo['pay_price']) . '元,奖励推广佣金' . floatval($virtualBrokeragePrice);
  336. //TODO 添加推广记录
  337. $res1 = UserBill::income('获得推广佣金', $userInfoTwo['spread_uid'], 'now_money', 'brokerage', $virtualBrokeragePrice, $orderInfo['id'], $balance, $mark);
  338. //TODO 添加用户余额
  339. $res2 = self::bcInc($userInfoTwo['spread_uid'], 'brokerage_price', $virtualBrokeragePrice, 'uid');
  340. //TODO 一级返佣成功 跳转二级返佣
  341. $res = $res1 && $res2;
  342. }
  343. if ($realBrokeragePrice > 0) {
  344. $spreadUserInfoTwo = User::getUserInfo($userInfoTwo['spread_uid']);
  345. //TODO 上级推广员返佣之后的金额
  346. $mark = '二级推广人' . $userInfo['nickname'] . '成功消费[实体产品]' . floatval($orderInfo['pay_price']) . '元,奖励推广佣金' . floatval($realBrokeragePrice);
  347. //TODO 添加推广记录
  348. $res = UserBill::income('获得推广佣金', $userInfoTwo['spread_uid'], 'now_money', 'brokerage', $realBrokeragePrice, $orderInfo['id'], $spreadUserInfoTwo['brokerage_price'], $mark, 0);
  349. }
  350. // $res = $res && self::backOrderBrokerageTwo($orderInfo);
  351. // $open && self::checkTrans($res);
  352. return $res;
  353. }
  354. /**
  355. * 发放实际商品佣金
  356. * @param $orderInfo
  357. * @return bool
  358. * @throws DataNotFoundException
  359. * @throws DbException
  360. * @throws ModelNotFoundException
  361. */
  362. public static function sendBackOrderBrokerage($orderInfo)
  363. {
  364. $list = UserBill::where(['link_id' => $orderInfo['id'], 'type' => 'brokerage', 'category' => 'now_money', 'pm' => 1, 'status' => 0])->select();
  365. if ($list) {
  366. self::beginTrans();
  367. try {
  368. foreach ($list as $v) {
  369. self::bcInc($v['uid'], 'brokerage_price', $v['number'], 'uid');
  370. $balance = self::getUserInfo($v['uid'])['brokerage_price'];
  371. UserBill::where('id', $v['id'])->update(['add_time' => time(), 'status' => 1, 'balance' => $balance]);
  372. }
  373. self::commitTrans();
  374. return true;
  375. } catch (Exception $e) {
  376. self::rollbackTrans();
  377. return false;
  378. }
  379. }
  380. return true;
  381. }
  382. /**
  383. * 获取推荐人 暂无使用
  384. * @param $uid
  385. * @param $page
  386. * @param $limit
  387. * @return mixed
  388. */
  389. public static function getSpreadList($uid, $page, $limit)
  390. {
  391. $list = self::where('spread_uid', $uid)->field('uid,nickname,avatar,add_time')->page($page, $limit)->order('add_time DESC')->select();
  392. foreach ($list as $k => $user) {
  393. $list[$k]['add_time'] = date('Y/m/d', $user['add_time']);
  394. $list[$k]['price'] = StoreOrder::getUserPrice($user['uid']);
  395. }
  396. $count = self::where('spread_uid', $uid)->field('uid,nickname,avatar,add_time')->count();
  397. $data['count'] = $count;
  398. $data['list'] = $list;
  399. return $data;
  400. }
  401. /**
  402. * 获取某个用户的下级uid
  403. * @param $uid
  404. * @return array
  405. */
  406. public static function getOneSpreadUid($uid)
  407. {
  408. return self::where('spread_uid', $uid)->column('uid');
  409. }
  410. /**
  411. * 修改个人信息
  412. * @param $avatar 头像
  413. * @param $nickname 昵称
  414. * @param $uid 用户uid
  415. * @return bool
  416. */
  417. public static function editUser($avatar, $nickname, $uid)
  418. {
  419. return self::edit(['avatar' => $avatar, 'nickname' => $nickname], $uid, 'uid');
  420. }
  421. /**
  422. * TODO 获取推广人数 一级
  423. * @param int $uid
  424. * @return bool|int|string
  425. */
  426. public static function getSpreadCount($uid = 0)
  427. {
  428. if (!$uid) return false;
  429. return self::where('spread_uid', $uid)->count();
  430. }
  431. /**
  432. * 修改当前用户的推广人数
  433. * @param $uid
  434. */
  435. public static function setUserSpreadCount($uid)
  436. {
  437. if (!$uid) return true;
  438. if (self::getSpreadCount($uid) > 0) {
  439. self::where('uid', $uid)->update(['spread_count' => 0]);
  440. } else {
  441. self::where('uid', $uid)->update(['spread_count' => 0]);
  442. return true;
  443. }
  444. return self::where('uid', $uid)->update(['spread_count' => self::getSpreadCount($uid)]);
  445. }
  446. /**
  447. * TODO 获取推广人数 二级
  448. * @param int $uid
  449. * @return bool|int|string
  450. */
  451. public static function getSpreadLevelCount($uid = 0)
  452. {
  453. if (!$uid) return false;
  454. $uidSubordinate = self::where('spread_uid', $uid)->column('uid');
  455. if (!count($uidSubordinate)) return 0;
  456. return self::where('spread_uid', 'IN', implode(',', $uidSubordinate))->count();
  457. }
  458. /**
  459. * 获取用户下级推广人
  460. * @param int $uid 当前用户
  461. * @param int $grade 等级 0 一级 1 二级
  462. * @param string $orderBy 排序
  463. * @param string $keyword
  464. * @param int $page
  465. * @param int $limit
  466. * @return array|bool
  467. */
  468. public static function getUserSpreadGrade($uid = 0, $grade = 0, $orderBy = '', $keyword = '', $page = 0, $limit = 20)
  469. {
  470. if (!$uid) return [];
  471. $gradeGroup = [0, 1];
  472. if (!in_array($grade, $gradeGroup)) return self::setErrorInfo('等级错误');
  473. $userStair = self::where('spread_uid', $uid)->column('uid');
  474. if (!count($userStair)) return [];
  475. if ($grade == 0) return self::getUserSpreadCountList(implode(',', $userStair), $orderBy, $keyword, $page, $limit);
  476. $userSecondary = self::where('spread_uid', 'in', implode(',', $userStair))->column('uid');
  477. halt(self::getUserSpreadCountList(implode(',', $userSecondary), $orderBy, $keyword, $page, $limit));
  478. return self::getUserSpreadCountList(implode(',', $userSecondary), $orderBy, $keyword, $page, $limit);
  479. }
  480. /**
  481. * 获取团队信息
  482. * @param $uid
  483. * @param string $orderBy
  484. * @param string $keyword
  485. * @param int $page
  486. * @param int $limit
  487. * @return array
  488. */
  489. public static function getUserSpreadCountList($uid, $orderBy = '', $keyword = '', $page = 0, $limit = 20)
  490. {
  491. $model = new self;
  492. if ($orderBy === '') $orderBy = 'u.add_time desc';
  493. $model = $model->alias(' u');
  494. $sql = StoreOrder::where('o.paid', 1)->group('o.uid')->field(['SUM(o.pay_price) as numberCount', 'o.uid', 'o.order_id'])
  495. ->where('o.is_del', 0)->where('o.is_system_del', 0)->alias('o')->fetchSql(true)->select();
  496. $model = $model->join("(" . $sql . ") p", 'u.uid = p.uid', 'LEFT');
  497. $model = $model->where('u.uid', 'IN', $uid);
  498. $model = $model->field("u.uid,u.nickname,u.phone,from_unixtime(u.add_time,'%Y/%m/%d') as time,u.spread_count as childCount,u.pay_count as orderCount,p.numberCount,u.account");
  499. if (strlen(trim($keyword))) $model = $model->where('u.nickname|u.phone', 'like', "%$keyword%");
  500. $model = $model->group('u.uid');
  501. $model = $model->order($orderBy);
  502. $model = $model->page($page, $limit);
  503. $list = $model->select();
  504. if ($list) return $list;
  505. else return [];
  506. }
  507. /**
  508. * 设置用户的上级关系
  509. * @param $uid 用户uid
  510. * @param $spreadUid 上级用户uid
  511. * @return User|bool
  512. * @throws DataNotFoundException
  513. * @throws ModelNotFoundException
  514. * @throws DbException
  515. */
  516. public static function setSpreadUid($uid, $spreadUid)
  517. {
  518. return UserSpread::setSpread($uid, $spreadUid);
  519. // 自己不能绑定自己为上级
  520. // if ($uid == $spreadUid) return false;
  521. // //TODO 获取后台分销类型
  522. // $storeBrokerageStatus = sys_config('store_brokerage_statu');
  523. // $storeBrokerageStatus = $storeBrokerageStatus ? $storeBrokerageStatus : 1;
  524. // if ($storeBrokerageStatus == 1) {
  525. // $spreadCount = self::where('uid', $spreadUid)->count();
  526. // if ($spreadCount) {
  527. // $spreadInfo = self::where('uid', $spreadUid)->find();
  528. // if ($spreadInfo->is_promoter) {
  529. // //TODO 只有扫码才可以获得推广权限
  530. // if (isset($wechatUser['isPromoter'])) $data['is_promoter'] = 1;
  531. // }
  532. // }
  533. // }
  534. // return self::where('uid', $uid)->update(['spread_uid' => $spreadUid, 'spread_time' => time()]);
  535. }
  536. /**
  537. * 判断上下级关系是否存在
  538. * @param $uid
  539. * @param $spreadUid
  540. * @return bool|int
  541. */
  542. public static function validSpread($uid, $spreadUid)
  543. {
  544. if (!$uid || !$spreadUid) return false;
  545. return self::where('uid', $uid)->where('spread_uid', $spreadUid)->count();
  546. }
  547. /**
  548. * H5用户注册
  549. * @param $account
  550. * @param $password
  551. * @param $spread
  552. * @return bool
  553. * @throws DataNotFoundException
  554. * @throws DbException
  555. * @throws ModelNotFoundException
  556. */
  557. public static function register($account, $password, $spread, $payment_pas)
  558. {
  559. if (self::be(['account' => $account])) return self::setErrorInfo('用户已存在');
  560. $phone = $account;
  561. $data['account'] = $account;
  562. $data['pwd'] = md5($password);
  563. $data['phone'] = $phone;
  564. // if ($spread) {
  565. // $data['spread_uid'] = $spread;
  566. // $data['spread_time'] = time();
  567. // }
  568. $data['real_name'] = '';
  569. $data['birthday'] = 0;
  570. $data['card_id'] = '';
  571. $data['mark'] = '';
  572. $data['addres'] = '';
  573. $data['user_type'] = 'h5';
  574. $data['add_time'] = time();
  575. $data['add_ip'] = app('request')->ip();
  576. $data['last_time'] = time();
  577. $data['last_ip'] = app('request')->ip();
  578. $data['nickname'] = substr(md5($account . time()), 0, 12);
  579. $data['avatar'] = $data['headimgurl'] = sys_config('h5_avatar');
  580. $data['city'] = '';
  581. $data['language'] = '';
  582. $data['province'] = '';
  583. $data['country'] = '';
  584. $data['payment_pas'] = md5($payment_pas.'sxg');
  585. self::beginTrans();
  586. $res2 = WechatUser::create($data);
  587. $data['uid'] = $res2->uid;
  588. $res1 = self::create($data);
  589. $res = $res1 && $res2 && UserSpread::setSpread($data['uid'], $spread);
  590. self::checkTrans($res);
  591. return $res;
  592. }
  593. /**
  594. * 密码修改
  595. * @param $account
  596. * @param $password
  597. * @return User|bool
  598. */
  599. public static function reset($account, $password)
  600. {
  601. if (!self::be(['account' => $account])) return self::setErrorInfo('用户不存在');
  602. $count = self::where('account', $account)->where('pwd', md5($password))->count();
  603. if ($count) return true;
  604. return self::where('account', $account)->update(['pwd' => md5($password)]);
  605. }
  606. /**
  607. * 获取手机号是否注册
  608. * @param $phone
  609. * @return bool
  610. */
  611. public static function checkPhone($phone)
  612. {
  613. return self::be(['account' => $phone]);
  614. }
  615. /**
  616. * 获取推广人
  617. * @param $data 查询条件
  618. * @return array
  619. * @throws DataNotFoundException
  620. * @throws ModelNotFoundException
  621. * @throws \think\exception\DbException
  622. */
  623. public static function getRankList($data)
  624. {
  625. switch ($data['type']) {
  626. case 'week':
  627. $startTime = strtotime('this week');
  628. $endTime = time();
  629. break;
  630. case 'month':
  631. $startTime = strtotime('last month');
  632. $endTime = time();
  633. break;
  634. }
  635. $list = self::alias('t0')
  636. ->field('t0.uid,t0.spread_uid,count(t1.spread_uid) AS count,t0.add_time,t0.nickname,t0.avatar')
  637. ->join('user t1', 't0.uid = t1.spread_uid', 'LEFT')
  638. ->where('t1.spread_uid', '<>', 0)
  639. ->order('count desc')
  640. ->order('t0.uid desc')
  641. ->where('t1.add_time', 'BETWEEN', [$startTime, $endTime])
  642. ->page($data['page'], $data['limit'])
  643. ->group('t0.uid')
  644. ->select();
  645. return count($list) ? $list->toArray() : [];
  646. }
  647. /**
  648. * 获取佣金排行
  649. * @param $data
  650. * @return array
  651. */
  652. public static function brokerageRank($data)
  653. {
  654. $model = self::where('status', 1);
  655. switch ($data['type']) {
  656. case 'week':
  657. $model = $model->whereIn('uid', function ($query) {
  658. $query->name('user_bill')->where('category', 'now_money')->where('type', 'brokerage')
  659. ->whereWeek('add_time')->field('uid');
  660. });
  661. break;
  662. case 'month':
  663. $model = $model->whereIn('uid', function ($query) {
  664. $query->name('user_bill')->where('category', 'now_money')->where('type', 'brokerage')
  665. ->whereMonth('add_time')->field('uid');
  666. });
  667. break;
  668. }
  669. $users = $model->field('uid,nickname,avatar,brokerage_price')->order('brokerage_price desc')
  670. ->page((int)$data['page'], (int)$data['limit'])->select();
  671. return count($users) ? $users->toArray() : [];
  672. }
  673. /**
  674. * 获取当前用户的佣金排行位置
  675. * @param $uid
  676. * @return int
  677. */
  678. public static function currentUserRank($type, $brokerage_price)
  679. {
  680. $model = self::where('status', 1);
  681. switch ($type) {
  682. case 'week':
  683. $model = $model->whereIn('uid', function ($query) {
  684. $query->name('user_bill')->where('category', 'now_money')->where('type', 'brokerage')
  685. ->whereWeek('add_time')->field('uid');
  686. });
  687. break;
  688. case 'month':
  689. $model = $model->whereIn('uid', function ($query) {
  690. $query->name('user_bill')->where('category', 'now_money')->where('type', 'brokerage')
  691. ->whereMonth('add_time')->field('uid');
  692. });
  693. break;
  694. }
  695. return $model->where('brokerage_price', '>', $brokerage_price)->count('uid');
  696. }
  697. /**
  698. * 直推奖励
  699. * @return void
  700. */
  701. public static function direct_push()
  702. {
  703. $auction = Auction::where('rend_time','<', date('H:i:s'))->select();
  704. foreach ($auction as $key => $value) {
  705. $auctionPush = AuctionPush::where('auction_id', '=',$value['id'])->where('add_time', '=', strtotime(date('Y-m-d', time())))->find();
  706. if (!$auctionPush){
  707. AuctionPush::beginTrans();
  708. if (strtotime($value['rend_time'])+1800 <= time()){
  709. //当前场次结束半个小时
  710. $order = AuctionOrder::alias('a')
  711. ->field('a.*')
  712. ->leftJoin('auction_product p', 'a.product_id = p.id')
  713. ->where([['a.auction_id', '=', $value['id']], ['a.status', '=', 2], ['p.is_show', '=', 1 ], ['frequency', '=', $value['frequency']]])
  714. ->select();
  715. if ($order){
  716. foreach ($order as $k => $v) {
  717. $user = User::where('uid', $v['uid'])->find();
  718. if ($user['spread_uid']){
  719. $spread = User::where('uid', $user['spread_uid'])->find();
  720. $bo = AuctionOrder::where('uid', $spread['uid'])->where('auction_id', $value['id'])->where('status', 2)->count();
  721. if ($bo > 0){
  722. $money = round($v['price'] * 0.003, 2);
  723. $spread['sp_final'] += $money;
  724. $spread->save();
  725. UserBill::income('奖励购物积分', $spread['uid'], 'sp_final', 'add_sp_final', $money, $user['uid'], $spread['sp_final'], '用户'.$user['account'].'购买成功,奖励购物积分');
  726. }
  727. }
  728. }
  729. }
  730. try {
  731. AuctionPush::create([
  732. 'auction_id' => $value['id'],
  733. 'add_time' => strtotime(date('Y-m-d', time()))
  734. ]);
  735. AuctionPush::commitTrans();
  736. } catch (\Exception $e) {
  737. AuctionPush::rollbackTrans();
  738. }
  739. }
  740. }
  741. }
  742. }
  743. /**
  744. * 分红奖励
  745. * @return void
  746. * @throws DataNotFoundException
  747. * @throws DbException
  748. * @throws ModelNotFoundException
  749. */
  750. public static function bonus(){
  751. if (!AuctionReward::where('create_time', strtotime(date('Y-m-d', time())))->find()){
  752. $config = SystemConfigService::more(['bonus', 'bonus_standard']);
  753. $user = self::field('uid,spread_uid, sp_final')->select();
  754. $user = empty($user) ? [] : $user->toArray();
  755. $time = strtotime(date('Y-m-d', strtotime('-1 day'))); // 昨天的时间
  756. $timet = strtotime(date('Y-m-d', time())); // 今天时间
  757. $orderMoney = AuctionOrder::where('status', '=',2)->where('create_time', '>=', $time)->where('create_time', '<=', $timet)->sum('price');// 找到昨天的总流水金额
  758. $moneys = [];
  759. foreach ($user as $k => $v){
  760. $bo = AuctionBooking::where('uid', '=', $v['uid'])->where('create_time', '>=', $time)->where('create_time', '<=', $timet)->find(); // 查看昨天有预约记录
  761. if ($bo){
  762. $dow = User::where('spread_uid', $v['uid'])->select()->toArray(); // 是否有下级
  763. if (!empty($dow)){
  764. foreach ($dow as $key => $value){
  765. $userDow[$value['uid']] = get_downline($user,$value['uid']);
  766. }
  767. foreach ($userDow as $dk => $dv){
  768. //查询出下级每个分支昨天流水多少
  769. $money = AuctionOrder::where('uid', $dk)->where('status',2)->sum('price');
  770. if ($dv){
  771. $money += AuctionOrder::where('uid', 'in', $dv)->where('status', '=', 2)->sum('price');
  772. }
  773. $moneys[] = $money;
  774. }
  775. sort($moneys); // 排序
  776. array_pop($moneys); // 删除最大的流水
  777. $sum = array_sum($moneys);
  778. if ($sum > (float)$config['bonus_standard']){
  779. $reward = round($orderMoney * ($config['bonus']/100), 2); // 奖励分红额度
  780. $v['sp_final'] += $reward;
  781. User::where('uid', $v['uid'])
  782. ->update(['sp_final' => $v['sp_final']]);
  783. UserBill::income('分红奖励', $v['uid'], 'sp_final', 'add_sp_final_bonus', $reward, 0, $v['sp_final'], '分红奖励');
  784. }
  785. unset($moneys);
  786. unset($userDow);
  787. }
  788. }
  789. }
  790. }
  791. }
  792. /**
  793. * KPI奖励
  794. * @return void
  795. * @throws DataNotFoundException
  796. * @throws DbException
  797. * @throws ModelNotFoundException
  798. */
  799. public static function kpi()
  800. {
  801. if (!AuctionReward::where('create_time', strtotime(date('Y-m-d', time())))->find()){
  802. $user = self::field('uid,spread_uid, sp_final,is_real')->select();
  803. $user = empty($user) ? [] : $user->toArray();
  804. $moneys = [];
  805. $time = strtotime(date('Y-m-d', strtotime('-1 day'))); // 昨天的时间
  806. $timet = strtotime(date('Y-m-d', time())); // 今天时间
  807. $userl = [];
  808. foreach ($user as $k => $v){
  809. if ($v['is_real'] == 1){// 是否是团队长,团队长有kpi奖励
  810. $bo = AuctionOrder::where('uid', '=', $v['uid'])->where('create_time', '>=', $time)->where('create_time', '<=', $timet)->where('status', '=', 2)->find(); // 查看昨天是否又购买成功记录
  811. if ($bo){
  812. $dow = User::where('spread_uid', $v['uid'])->select()->toArray(); // 是否有下级
  813. if (!empty($dow)){
  814. foreach ($dow as $key => $value){
  815. $userDow[$value['uid']] = get_downline($user,$value['uid']); // 获取到下级
  816. }
  817. foreach ($userDow as $dk => $dv){
  818. //查询出下级每个分支昨天流水多少
  819. $money = AuctionOrder::where('uid', $dk)->where('status',2)->sum('price');
  820. if ($dv){
  821. $money += AuctionOrder::where('uid', 'in', $dv)->where('status', '=', 2)->sum('price');
  822. }
  823. $moneys[$dk] = $money; // 查询到支线下级总额度
  824. }
  825. $userl = $moneys;
  826. sort($moneys); // 排序
  827. array_pop($moneys); // 删除最大的流水
  828. $sum = array_sum($moneys);
  829. $level = self::con($sum);
  830. if ($level > 0){
  831. // 到达奖励额度
  832. if (empty($v['spread_uid'])){
  833. // 没有上级
  834. foreach ($userl as $uk => $uv){
  835. $towdow = self::dow($uk);
  836. if ($level > $towdow){
  837. $reward = ($level - $towdow)/100; // 减掉下级获得的倍率
  838. $userl[$uk] = $uv * $reward;
  839. }elseif ($level == $towdow){
  840. $reward = $level/100; // 如果等级相同就只拿百分之十
  841. $userl[$uk] = ($uv * $reward) * 0.1;
  842. }
  843. }
  844. $userMoney = array_sum($userl);
  845. $v['sp_final'] += $userMoney;
  846. User::where('uid', $v['uid'])
  847. ->update(['sp_final' => $v['sp_final']]);
  848. UserBill::income('KPI奖励', $v['uid'], 'sp_final', 'add_sp_final_kpi', $userMoney, 0, $v['sp_final'], 'KPI奖励');
  849. }else{
  850. //有上级
  851. foreach ($userl as $uk => $uv){
  852. $towdow = self::dow($uk);
  853. if ($level > $towdow){
  854. $reward = ($level - $towdow)/100; // 减掉下级获得的倍率
  855. }elseif ($level == $towdow){
  856. $reward = ($level* 0.1)/100; // 如果下级等级相同就只拿百分之十
  857. }
  858. $userl[$uk] = $uv * $reward;
  859. }
  860. $plevel = self::dow($v['spread_uid']);
  861. $userMoney = array_sum($userl);
  862. if ($plevel == $level) {
  863. $userMoney = $userMoney * 0.9; // 如果和上级相同等级只拿百分之九十
  864. }
  865. $v['sp_final'] += $userMoney;
  866. User::where('uid', $v['uid'])
  867. ->update(['sp_final' => $v['sp_final']]);
  868. UserBill::income('KPI奖励', $v['uid'], 'sp_final', 'add_sp_final_kpi', $userMoney, 0, $v['sp_final'], 'KPI奖励');
  869. }
  870. }
  871. unset($userl);
  872. unset($moneys);
  873. unset($userDow);
  874. }
  875. }
  876. }
  877. }
  878. }
  879. }
  880. public static function dow($id)
  881. {
  882. $users = self::where('uid',$id)->find();
  883. if ($users['isis_real'] == 1){
  884. $user = self::field('uid,spread_uid, sp_final')->select();
  885. $dow = User::where('spread_uid', $id)->select()->toArray(); // 是否有下级
  886. if (!empty($dow)) {
  887. foreach ($dow as $key => $value) {
  888. $userDow[$value['uid']] = get_downline($user, $value['uid']);
  889. }
  890. foreach ($userDow as $dk => $dv) {
  891. //查询出下级每个分支昨天流水多少
  892. $money = AuctionOrder::where('uid', $dk)->where('status', 2)->sum('price');
  893. if ($dv) {
  894. $money += AuctionOrder::where('uid', 'in', $dv)->where('status', '=', 2)->sum('price');
  895. }
  896. $moneys[$dk] = $money;
  897. }
  898. sort($moneys); // 排序
  899. array_pop($moneys); // 删除最大的流水
  900. $sum = array_sum($moneys);
  901. $level = self::con($sum);
  902. return $level;
  903. }
  904. return 0;
  905. }else{
  906. return 0;
  907. }
  908. }
  909. public static function con($sum){
  910. //算出到达几级的奖励
  911. $config = SystemConfigService::more([
  912. 'level_one','one_standard','level_two','two_standard','level_three','three_standard','level_four','four_standard','level_five','five_standard'
  913. ]);
  914. $status = '';
  915. if ($sum < $config['one_standard']) $status = 0;
  916. if ($sum >= $config['one_standard'] and $sum < $config['two_standard']) $status = $config['level_one']; // 达标1级
  917. if ($sum >= $config['two_standard'] and $sum < $config['three_standard']) $status = $config['level_two'];// 达标2级
  918. if ($sum >= $config['three_standard'] and $sum < $config['four_standard']) $status = $config['level_three'];// 达标3级
  919. if ($sum >= $config['four_standard'] and $sum < $config['five_standard']) $status = $config['level_four'];// 达标4级
  920. if ($sum >= $config['five_standard']) $status = $config['level_five'];// 达标5级
  921. return $status;
  922. }
  923. /**
  924. * 更新奖励发放时间
  925. * @return void
  926. * @throws DataNotFoundException
  927. * @throws DbException
  928. * @throws ModelNotFoundException
  929. */
  930. public static function up_time()
  931. {
  932. if (!AuctionReward::where('create_time', strtotime(date('Y-m-d', time())))->find()){
  933. AuctionReward::create([
  934. 'create_time' => strtotime(date('Y-m-d', time()))
  935. ]);
  936. }
  937. }
  938. }