UserServices.php 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. //declare (strict_types=1);
  12. namespace app\services\user;
  13. use app\jobs\UserJob;
  14. use app\services\activity\bargain\StoreBargainServices;
  15. use app\services\activity\combination\StoreCombinationServices;
  16. use app\services\activity\seckill\StoreSeckillServices;
  17. use app\services\agent\AgentLevelServices;
  18. use app\services\BaseServices;
  19. use app\dao\user\UserDao;
  20. use app\services\activity\coupon\StoreCouponUserServices;
  21. use app\services\diy\DiyServices;
  22. use app\services\message\service\StoreServiceRecordServices;
  23. use app\services\message\service\StoreServiceServices;
  24. use app\services\order\OtherOrderServices;
  25. use app\services\order\StoreOrderCreateServices;
  26. use app\services\order\StoreOrderServices;
  27. use app\services\order\StoreOrderTakeServices;
  28. use app\services\other\QrcodeServices;
  29. use app\services\product\product\StoreProductRelationServices;
  30. use app\services\message\MessageSystemServices;
  31. use app\services\system\SystemUserLevelServices;
  32. use app\services\user\member\MemberCardServices;
  33. use app\services\wechat\WechatUserServices;
  34. use crmeb\exceptions\AdminException;
  35. use crmeb\services\CacheService;
  36. use crmeb\services\FormBuilder as Form;
  37. use crmeb\services\FormBuilder;
  38. use crmeb\services\WechatService;
  39. use think\Exception;
  40. use think\exception\ValidateException;
  41. use think\facade\Route as Url;
  42. /**
  43. *
  44. * Class UserServices
  45. * @package app\services\user
  46. * @method array getUserInfoArray(array $where, string $field, string $key) 根据条件查询对应的用户信息以数组形式返回
  47. * @method update($id, array $data, ?string $key = null) 修改数据
  48. * @method get($id, ?array $field = [], ?array $with = []) 获取一条数据
  49. * @method count(array $where) 获取指定条件下的数量
  50. * @method value(array $where, string $field) 获取指定的键值
  51. * @method bcInc($key, string $incField, string $inc, string $keyField = null, int $acc = 2) 高精度加法
  52. * @method bcDec($key, string $incField, string $inc, string $keyField = null, int $acc = 2) 高精度减法
  53. * @method getTrendData($time, $type, $timeType)
  54. * @method incPayCount(int $uid) 用户支付成功个数增加
  55. */
  56. class UserServices extends BaseServices
  57. {
  58. /**
  59. * UserServices constructor.
  60. * @param UserDao $dao
  61. */
  62. public function __construct(UserDao $dao)
  63. {
  64. $this->dao = $dao;
  65. }
  66. /**
  67. * 获取用户信息
  68. * @param $id
  69. * @param $field
  70. */
  71. public function getUserInfo(int $uid, $field = '*')
  72. {
  73. if (is_string($field)) $field = explode(',', $field);
  74. return $this->dao->get($uid, $field);
  75. }
  76. /**
  77. * 获取用户列表
  78. * @param array $where
  79. * @param string $field
  80. * @return array
  81. * @throws \think\db\exception\DataNotFoundException
  82. * @throws \think\db\exception\DbException
  83. * @throws \think\db\exception\ModelNotFoundException
  84. */
  85. public function getUserList(array $where, string $field): array
  86. {
  87. [$page, $limit] = $this->getPageValue();
  88. $list = $this->dao->getList($where, $field, $page, $limit);
  89. $count = $this->getCount($where);
  90. return compact('list', 'count');
  91. }
  92. /**
  93. * 列表条数
  94. * @param array $where
  95. * @return int
  96. */
  97. public function getCount(array $where, bool $is_list = false)
  98. {
  99. return $this->dao->getCount($where, $is_list);
  100. }
  101. /**
  102. * 保存用户信息
  103. * @param $user
  104. * @param int $spreadUid
  105. * @param string $userType
  106. * @return User|\think\Model
  107. */
  108. public function setUserInfo($user, int $spreadUid = 0, string $userType = 'wechat')
  109. {
  110. $data = [
  111. 'account' => $user['account'] ?? 'wx' . rand(1, 9999) . time(),
  112. 'pwd' => $user['pwd'] ?? md5('123456'),
  113. 'nickname' => $user['nickname'] ?? '',
  114. 'avatar' => $user['headimgurl'] ?? '',
  115. 'phone' => $user['phone'] ?? '',
  116. 'add_time' => time(),
  117. 'add_ip' => app()->request->ip(),
  118. 'last_time' => time(),
  119. 'last_ip' => app()->request->ip(),
  120. 'user_type' => $userType,
  121. 'staff_id' => $user['staff_id'] ?? 0,
  122. 'agent_id' => $user['agent_id'] ?? 0,
  123. 'division_id' => $user['division_id'] ?? 0,
  124. ];
  125. if ($spreadUid) {
  126. $data['spread_uid'] = $spreadUid;
  127. $data['spread_time'] = time();
  128. }
  129. $res = $this->dao->save($data);
  130. if (!$res)
  131. throw new AdminException('保存用户信息失败');
  132. //用户生成后置事件
  133. event('user.register', [$spreadUid, $userType, $user['nickname'], $res->uid, 1]);
  134. //推送消息
  135. event('notice.notice', [['spreadUid' => $spreadUid, 'user_type' => $userType, 'nickname' => $user['nickname']], 'bind_spread_uid']);
  136. return $res;
  137. }
  138. /**
  139. * 某些条件用户佣金总和
  140. * @param array $where
  141. * @return mixed
  142. */
  143. public function getSumBrokerage(array $where)
  144. {
  145. return $this->dao->getWhereSumField($where, 'brokerage_price');
  146. }
  147. /**
  148. * 根据条件获取用户指定字段列表
  149. * @param array $where
  150. * @param string $field
  151. * @param string $key
  152. * @return array
  153. */
  154. public function getColumn(array $where, string $field = '*', string $key = '')
  155. {
  156. return $this->dao->getColumn($where, $field, $key);
  157. }
  158. /**
  159. * 获取某个用户的推广下线
  160. */
  161. public function getSpreadList($uid)
  162. {
  163. $one_uids = $this->dao->getColumn(['spread_uid' => $uid], 'uid');
  164. $two_uids = $this->dao->getColumn([['spread_uid', 'in', $one_uids], ['spread_uid', '<>', 0]], 'uid');
  165. $uids = array_merge($one_uids, $two_uids);
  166. [$page, $limit] = $this->getPageValue();
  167. $list = $this->dao->getList(['uid' => $uids], 'uid,nickname,real_name,avatar,add_time', $page, $limit);
  168. foreach ($list as $k => $user) {
  169. $list[$k]['type'] = in_array($user['uid'], $one_uids) ? '一级' : '二级';
  170. $list[$k]['add_time'] = date('Y-m-d', $user['add_time']);
  171. }
  172. $count = count($uids);
  173. return compact('count', 'list');
  174. }
  175. /**查找多个uid信息
  176. * @param $uids
  177. * @param bool $field
  178. * @return UserDao|bool|\crmeb\basic\BaseModel|mixed|\think\Collection
  179. */
  180. public function getUserListByUids($uids, $field = false)
  181. {
  182. if (!$uids || !is_array($uids)) return false;
  183. return $this->dao->getUserListByUids($uids, $field);
  184. }
  185. /**
  186. * 获取分销用户
  187. * @param array $where
  188. * @param string $field
  189. * @return array
  190. * @throws \think\db\exception\DataNotFoundException
  191. * @throws \think\db\exception\DbException
  192. * @throws \think\db\exception\ModelNotFoundException
  193. */
  194. public function getAgentUserList(array $where = [], string $field = '*', $is_page = true)
  195. {
  196. $where_data['status'] = 1;
  197. $where_data['is_promoter'] = 1;
  198. $where_data['spread_open'] = 1;
  199. //人人分销时 去除分销员字段的限制
  200. $store_brokerage_statu = sys_config('store_brokerage_statu');
  201. if ($store_brokerage_statu == 2) unset($where_data['is_promoter']);
  202. if (isset($where['nickname']) && $where['nickname'] !== '') {
  203. $where_data['like'] = $where['nickname'];
  204. }
  205. if (isset($where['data']) && $where['data']) {
  206. $where_data['time'] = $where['data'];
  207. }
  208. [$page, $limit] = $this->getPageValue($is_page);
  209. $list = $this->dao->getAgentUserList($where_data, $field, $page, $limit);
  210. $count = $this->dao->count($where_data);
  211. return compact('count', 'list');
  212. }
  213. /**
  214. * 获取分销员ids
  215. * @param array $where
  216. * @return array
  217. */
  218. public function getAgentUserIds(array $where)
  219. {
  220. $where['status'] = 1;
  221. if (sys_config('store_brokerage_statu') != 2) $where['is_promoter'] = 1;
  222. $where['spread_open'] = 1;
  223. if (isset($where['nickname']) && $where['nickname'] !== '') {
  224. $where['like'] = $where['nickname'];
  225. }
  226. if (isset($where['data']) && $where['data']) {
  227. $where['time'] = $where['data'];
  228. }
  229. return $this->dao->getAgentUserIds($where);
  230. }
  231. /**
  232. * 获取推广人列表
  233. * @param array $where
  234. * @param string $field
  235. * @param int $page
  236. * @param int $limit
  237. * @throws \think\db\exception\DataNotFoundException
  238. * @throws \think\db\exception\DbException
  239. * @throws \think\db\exception\ModelNotFoundException
  240. */
  241. public function getSairList(array $where, string $field = '*')
  242. {
  243. $where_data = [];
  244. if (isset($where['uid'])) {
  245. if (isset($where['type'])) {
  246. $type = (int)$where['type'];
  247. $type = in_array($type, [1, 2]) ? $type : 0;
  248. $uids = $this->getUserSpredadUids((int)$where['uid'], $type);
  249. $where_data['uid'] = count($uids) > 0 ? $uids : 0;
  250. }
  251. if (isset($where['data']) && $where['data']) {
  252. $where_data['time'] = $where['data'];
  253. }
  254. if (isset($where['nickname']) && $where['nickname']) {
  255. $where_data['like'] = $where['nickname'];
  256. }
  257. $where_data['status'] = 1;
  258. }
  259. [$page, $limit] = $this->getPageValue();
  260. $list = $this->dao->getSairList($where_data, '*', $page, $limit);
  261. $count = $this->dao->count($where_data);
  262. return compact('list', 'count');
  263. }
  264. /**
  265. * 获取推广人统计
  266. * @param array $where
  267. * @param string $field
  268. * @param int $page
  269. * @param int $limit
  270. * @throws \think\db\exception\DataNotFoundException
  271. * @throws \think\db\exception\DbException
  272. * @throws \think\db\exception\ModelNotFoundException
  273. */
  274. public function getSairCount(array $where)
  275. {
  276. $where_data = [];
  277. if (isset($where['uid'])) {
  278. if (isset($where['type'])) {
  279. $uids = $this->getColumn(['spread_uid' => $where['uid']], 'uid');
  280. switch ((int)$where['type']) {
  281. case 1:
  282. $where_data['uid'] = count($uids) > 0 ? $uids : 0;
  283. break;
  284. case 2:
  285. if (count($uids))
  286. $spread_uid_two = $this->dao->getColumn([['spread_uid', 'IN', $uids]], 'uid');
  287. else
  288. $spread_uid_two = [];
  289. $where_data['uid'] = count($spread_uid_two) > 0 ? $spread_uid_two : 0;
  290. break;
  291. default:
  292. if (count($uids)) {
  293. if ($spread_uid_two = $this->dao->getColumn([['spread_uid', 'IN', $uids]], 'uid')) {
  294. $uids = array_merge($uids, $spread_uid_two);
  295. $uids = array_unique($uids);
  296. $uids = array_merge($uids);
  297. }
  298. }
  299. $where_data['uid'] = count($uids) > 0 ? $uids : 0;
  300. break;
  301. }
  302. }
  303. if (isset($where['data']) && $where['data']) {
  304. $where_data['time'] = $where['data'];
  305. }
  306. if (isset($where['nickname']) && $where['nickname']) {
  307. $where_data['like'] = $where['nickname'];
  308. }
  309. $where_data['status'] = 1;
  310. }
  311. return $this->dao->count($where_data);
  312. }
  313. /**
  314. * 写入用户信息
  315. * @param array $data
  316. * @return bool
  317. */
  318. public function create(array $data)
  319. {
  320. if (!$this->dao->save($data))
  321. throw new AdminException('写入失败');
  322. return true;
  323. }
  324. /**
  325. * 重置密码
  326. * @param $id
  327. * @param string $password
  328. * @return mixed
  329. */
  330. public function resetPwd(int $uid, string $password)
  331. {
  332. if (!$this->dao->update($uid, ['pwd' => $password]))
  333. throw new AdminException('密码重置失败');
  334. return true;
  335. }
  336. /**
  337. * 增加推广人数
  338. * @param int $uid
  339. * @param int $num
  340. * @return bool
  341. * @throws Exception
  342. */
  343. public function incSpreadCount(int $uid, int $num = 1)
  344. {
  345. if (!$this->dao->incField($uid, 'spread_count', $num))
  346. throw new Exception('增加推广人数失败');
  347. return true;
  348. }
  349. /**
  350. * 设置用户登录类型
  351. * @param int $uid
  352. * @param string $type
  353. * @return bool
  354. * @throws Exception
  355. */
  356. public function setLoginType(int $uid, string $type = 'h5')
  357. {
  358. if (!$this->dao->update($uid, ['login_type' => $type]))
  359. throw new Exception('设置登录类型失败');
  360. return true;
  361. }
  362. /**
  363. * 设置推广员
  364. * @param int $uid
  365. * @param int $is_promoter
  366. * @return bool
  367. * @throws Exception
  368. */
  369. public function setIsPromoter(int $uid, $is_promoter = 1)
  370. {
  371. if (!$this->dao->update($uid, ['is_promoter' => $is_promoter]))
  372. throw new Exception('设置推广员失败');
  373. return true;
  374. }
  375. /**
  376. * 设置用户分组
  377. * @param $uids
  378. * @param int $group_id
  379. */
  380. public function setUserGroup($uids, int $group_id)
  381. {
  382. return $this->dao->batchUpdate($uids, ['group_id' => $group_id], 'uid');
  383. }
  384. /**
  385. * 增加用户余额
  386. * @param int $uid
  387. * @param float $old_now_money
  388. * @param float $now_money
  389. * @return bool
  390. * @throws Exception
  391. */
  392. public function addNowMoney(int $uid, $old_now_money, $now_money)
  393. {
  394. if (!$this->dao->update($uid, ['now_money' => bcadd($old_now_money, $now_money, 2)]))
  395. throw new Exception('增加用户余额失败');
  396. return true;
  397. }
  398. /**
  399. * 减少用户余额
  400. * @param int $uid
  401. * @param float $old_now_money
  402. * @param float $now_money
  403. * @return bool
  404. * @throws Exception
  405. */
  406. public function cutNowMoney(int $uid, $old_now_money, $now_money)
  407. {
  408. if ($old_now_money > $now_money) {
  409. $money = ['now_money' => bcsub($old_now_money, $now_money, 2)];
  410. } else {
  411. $money = ['now_money' => 0];
  412. }
  413. if (!$this->dao->update($uid, $money, 'uid'))
  414. throw new Exception('减少用户余额失败');
  415. return true;
  416. }
  417. /**
  418. * 减少用户佣金
  419. * @param int $uid
  420. * @param float $brokerage_price
  421. * @param float $price
  422. * @return bool
  423. * @throws Exception
  424. */
  425. public function cutBrokeragePrice(int $uid, $brokerage_price, $price)
  426. {
  427. if (!$this->dao->update($uid, ['brokerage_price' => bcsub($brokerage_price, $price, 2)]))
  428. throw new Exception('减少用户佣金失败');
  429. return true;
  430. }
  431. /**
  432. * 增加用户积分
  433. * @param int $uid
  434. * @param float $old_integral
  435. * @param float $integral
  436. * @return bool
  437. * @throws Exception
  438. */
  439. public function addIntegral(int $uid, $old_integral, $integral)
  440. {
  441. if (!$this->dao->update($uid, ['integral' => bcadd($old_integral, $integral, 2)]))
  442. throw new Exception('增加用户积分失败');
  443. return true;
  444. }
  445. /**
  446. * 减少用户积分
  447. * @param int $uid
  448. * @param float $old_integral
  449. * @param float $integral
  450. * @return bool
  451. * @throws Exception
  452. */
  453. public function cutIntegral(int $uid, $old_integral, $integral)
  454. {
  455. if (!$this->dao->update($uid, ['integral' => bcsub($old_integral, $integral, 2)]))
  456. throw new Exception('减少用户积分失败');
  457. return true;
  458. }
  459. /**
  460. * 增加用户经验
  461. * @param int $uid
  462. * @param float $old_exp
  463. * @param float $exp
  464. * @return bool
  465. * @throws Exception
  466. */
  467. public function addExp(int $uid, float $old_exp, float $exp)
  468. {
  469. if (!$this->dao->update($uid, ['exp' => bcadd($old_exp, $exp, 2)]))
  470. throw new Exception('增加用户经验失败');
  471. return true;
  472. }
  473. /**
  474. * 减少用户经验
  475. * @param int $uid
  476. * @param float $old_exp
  477. * @param float $exp
  478. * @return bool
  479. * @throws Exception
  480. */
  481. public function cutExp(int $uid, float $old_exp, float $exp)
  482. {
  483. if (!$this->dao->update($uid, ['exp' => bcsub($old_exp, $exp, 2)]))
  484. throw new Exception('减少用户经验失败');
  485. return true;
  486. }
  487. /**
  488. * 获取用户标签
  489. * @param $uid
  490. * @return \think\Collection
  491. * @throws \think\db\exception\DataNotFoundException
  492. * @throws \think\db\exception\DbException
  493. * @throws \think\db\exception\ModelNotFoundException
  494. */
  495. public function getUserLablel(array $uids)
  496. {
  497. /** @var UserLabelRelationServices $services */
  498. $services = app()->make(UserLabelRelationServices::class);
  499. $userlabels = $services->getUserLabelList($uids);
  500. $data = [];
  501. foreach ($uids as $uid) {
  502. $labels = array_filter($userlabels, function ($item) use ($uid) {
  503. if ($item['uid'] == $uid) {
  504. return true;
  505. }
  506. });
  507. $data[$uid] = implode(',', array_column($labels, 'label_name'));
  508. }
  509. return $data;
  510. }
  511. /**
  512. * 显示资源列表头部
  513. * @return array[]
  514. */
  515. public function typeHead()
  516. {
  517. //全部会员
  518. $all = $this->getCount([]);
  519. /** @var UserWechatuserServices $userWechatUser */
  520. $userWechatUser = app()->make(UserWechatuserServices::class);
  521. //小程序会员
  522. $routine = $userWechatUser->getCount([['w.user_type', '=', 'routine']]);
  523. //公众号会员
  524. $wechat = $userWechatUser->getCount([['w.user_type', '=', 'wechat']]);
  525. //H5会员
  526. $h5 = $userWechatUser->getCount(['w.openid' => '', 'u.user_type' => 'h5']);
  527. //pc会员
  528. $pc = $userWechatUser->getCount(['w.openid' => '', 'u.user_type' => 'pc']);
  529. return [
  530. ['user_type' => '', 'name' => '全部会员', 'count' => $all],
  531. ['user_type' => 'routine', 'name' => '小程序会员', 'count' => $routine],
  532. ['user_type' => 'wechat', 'name' => '公众号会员', 'count' => $wechat],
  533. ['user_type' => 'h5', 'name' => 'H5会员', 'count' => $h5],
  534. ['user_type' => 'pc', 'name' => 'PC会员', 'count' => $pc],
  535. ];
  536. }
  537. /**
  538. * 会员列表
  539. * @param array $where
  540. * @return array
  541. */
  542. public function index(array $where)
  543. {
  544. /** @var UserWechatuserServices $userWechatUser */
  545. $userWechatUser = app()->make(UserWechatuserServices::class);
  546. $fields = 'u.*,w.country,w.province,w.city,w.sex,w.unionid,w.openid,w.user_type as w_user_type,w.groupid,w.tagid_list,w.subscribe,w.subscribe_time';
  547. [$list, $count] = $userWechatUser->getWhereUserList($where, $fields);
  548. if ($list) {
  549. $uids = array_column($list, 'uid');
  550. $userlabel = $this->getUserLablel($uids);
  551. $userGroup = app()->make(UserGroupServices::class)->getUsersGroupName(array_unique(array_column($list, 'group_id')));
  552. $userExtract = app()->make(UserExtractServices::class)->getUsersSumList($uids);
  553. $levelName = app()->make(SystemUserLevelServices::class)->getUsersLevel(array_unique(array_column($list, 'level')));
  554. $userLevel = app()->make(UserLevelServices::class)->getUsersLevelInfo($uids);
  555. $spread_names = $this->dao->getColumn([['uid', 'in', array_unique(array_column($list, 'spread_uid'))]], 'nickname', 'uid');
  556. foreach ($list as &$item) {
  557. if (empty($item['addres'])) {
  558. if (!empty($item['country']) || !empty($item['province']) || !empty($item['city'])) {
  559. $item['addres'] = $item['country'] . $item['province'] . $item['city'];
  560. }
  561. }
  562. $item['status'] = ($item['status'] == 1) ? '正常' : '禁止';
  563. $item['birthday'] = $item['birthday'] ? date('Y-m-d', (int)$item['birthday']) : '';
  564. $item['extract_count_price'] = $userExtract[$item['uid']] ?? 0;//累计提现
  565. $item['spread_uid_nickname'] = $item['spread_uid'] ? ($spread_names[$item['spread_uid']] ?? '') . '/' . $item['spread_uid'] : '无';
  566. //用户类型
  567. if ($item['user_type'] == 'routine') {
  568. $item['user_type'] = '小程序';
  569. } else if ($item['user_type'] == 'wechat') {
  570. $item['user_type'] = '公众号';
  571. } else if ($item['user_type'] == 'h5') {
  572. $item['user_type'] = 'H5';
  573. } else if ($item['user_type'] == 'pc') {
  574. $item['user_type'] = 'PC';
  575. } else if ($item['user_type'] == 'app' || $item['user_type'] == 'apple') {
  576. $item['user_type'] = 'APP';
  577. } else $item['user_type'] = '其他';
  578. if ($item['sex'] == 1) {
  579. $item['sex'] = '男';
  580. } else if ($item['sex'] == 2) {
  581. $item['sex'] = '女';
  582. } else $item['sex'] = '保密';
  583. //等级名称
  584. $item['level'] = $levelName[$item['level']] ?? '无';
  585. //分组名称
  586. $item['group_id'] = $userGroup[$item['group_id']] ?? '无';
  587. //用户等级
  588. $item['vip_name'] = false;
  589. $levelinfo = $userLevel[$item['uid']] ?? null;
  590. if ($levelinfo) {
  591. if ($levelinfo && ($levelinfo['is_forever'] || time() < $levelinfo['valid_time'])) {
  592. $item['vip_name'] = $item['level'] != '无' ? $item['level'] : false;
  593. }
  594. }
  595. $item['labels'] = $userlabel[$item['uid']] ?? '';
  596. $item['isMember'] = $item['is_money_level'] > 0 ? 1 : 0;
  597. }
  598. }
  599. return compact('count', 'list');
  600. }
  601. /**
  602. * 获取修改页面数据
  603. * @param int $id
  604. * @return array
  605. * @throws \FormBuilder\Exception\FormBuilderException
  606. */
  607. public function edit(int $id)
  608. {
  609. $user = $this->getUserInfo($id);
  610. if (!$user)
  611. throw new AdminException('数据不存在');
  612. $f = array();
  613. $f[] = Form::input('uid', '用户编号', $user->getData('uid'))->disabled(true);
  614. $f[] = Form::input('real_name', '真实姓名', $user->getData('real_name'));
  615. $f[] = Form::input('phone', '手机号码', $user->getData('phone'));
  616. $f[] = Form::date('birthday', '生日', $user->getData('birthday') ? date('Y-m-d', $user->getData('birthday')) : '');
  617. $f[] = Form::input('card_id', '身份证号', $user->getData('card_id'));
  618. $f[] = Form::input('addres', '用户地址', $user->getData('addres'));
  619. $f[] = Form::textarea('mark', '用户备注', $user->getData('mark'));
  620. $f[] = Form::input('pwd', '登录密码')->type('password')->placeholder('不改密码请留空');
  621. $f[] = Form::input('true_pwd', '确认密码')->type('password')->placeholder('不改密码请留空');
  622. //查询高于当前会员的所有会员等级
  623. // $grade = app()->make(UserLevelServices::class)->getUerLevelInfoByUid($id, 'grade');
  624. $systemLevelList = app()->make(SystemUserLevelServices::class)->getWhereLevelList([], 'id,name');
  625. $setOptionLevel = function () use ($systemLevelList) {
  626. $menus = [];
  627. foreach ($systemLevelList as $menu) {
  628. $menus[] = ['value' => $menu['id'], 'label' => $menu['name']];
  629. }
  630. return $menus;
  631. };
  632. $f[] = Form::select('level', '用户等级', (int)$user->getData('level'))->setOptions(FormBuilder::setOptions($setOptionLevel))->filterable(true);
  633. $systemGroupList = app()->make(UserGroupServices::class)->getGroupList();
  634. $setOptionGroup = function () use ($systemGroupList) {
  635. $menus = [];
  636. foreach ($systemGroupList as $menu) {
  637. $menus[] = ['value' => $menu['id'], 'label' => $menu['group_name']];
  638. }
  639. return $menus;
  640. };
  641. $f[] = Form::select('group_id', '用户分组', $user->getData('group_id'))->setOptions(FormBuilder::setOptions($setOptionGroup))->filterable(true);
  642. $systemLabelList = app()->make(UserLabelServices::class)->getLabelList();
  643. $labels = app()->make(UserLabelRelationServices::class)->getUserLabels($user['uid']);
  644. $setOptionLabel = function () use ($systemLabelList) {
  645. $menus = [];
  646. foreach ($systemLabelList as $menu) {
  647. $menus[] = ['value' => $menu['id'], 'label' => $menu['label_name']];
  648. }
  649. return $menus;
  650. };
  651. $f[] = Form::select('label_id', '用户标签', $labels)->setOptions(FormBuilder::setOptions($setOptionLabel))->filterable(true)->multiple(true);
  652. $f[] = Form::radio('spread_open', '推广资格', $user->getData('spread_open'))->info('禁用用户的推广资格后,在任何分销模式下该用户都无分销权限')->options([['value' => 1, 'label' => '启用'], ['value' => 0, 'label' => '禁用']]);
  653. //分销模式 人人分销
  654. $storeBrokerageStatus = sys_config('store_brokerage_statu', 1);
  655. if ($storeBrokerageStatus == 1) {
  656. $f[] = Form::radio('is_promoter', '推广员权限', $user->getData('is_promoter'))->info('指定分销模式下,开启或关闭用户的推广权限')->options([['value' => 1, 'label' => '开启'], ['value' => 0, 'label' => '关闭']]);
  657. }
  658. $f[] = Form::radio('status', '用户状态', $user->getData('status'))->options([['value' => 1, 'label' => '开启'], ['value' => 0, 'label' => '锁定']]);
  659. return create_form('编辑', $f, Url::buildUrl('/user/user/' . $id), 'PUT');
  660. }
  661. /**
  662. * 添加用户表单
  663. * @param int $id
  664. * @return array
  665. * @throws \FormBuilder\Exception\FormBuilderException
  666. */
  667. public function saveForm()
  668. {
  669. $f = array();
  670. $f[] = Form::input('real_name', '真实姓名', '')->placeholder('请输入真实姓名');
  671. $f[] = Form::input('phone', '手机号码', '')->placeholder('请输入手机号码')->required();
  672. $f[] = Form::date('birthday', '生日', '')->placeholder('请选择生日');
  673. $f[] = Form::input('card_id', '身份证号', '')->placeholder('请输入身份证号');
  674. $f[] = Form::input('addres', '用户地址', '')->placeholder('请输入用户地址');
  675. $f[] = Form::textarea('mark', '用户备注', '')->placeholder('请输入用户备注');
  676. $f[] = Form::input('pwd', '登录密码')->type('password')->placeholder('请输入登录密码');
  677. $f[] = Form::input('true_pwd', '确认密码')->type('password')->placeholder('请再次确认密码');
  678. $systemLevelList = app()->make(SystemUserLevelServices::class)->getWhereLevelList([], 'id,name');
  679. $setOptionLevel = function () use ($systemLevelList) {
  680. $menus = [];
  681. foreach ($systemLevelList as $menu) {
  682. $menus[] = ['value' => $menu['id'], 'label' => $menu['name']];
  683. }
  684. return $menus;
  685. };
  686. $f[] = Form::select('level', '用户等级', '')->setOptions(FormBuilder::setOptions($setOptionLevel))->filterable(true);
  687. $systemGroupList = app()->make(UserGroupServices::class)->getGroupList();
  688. $setOptionGroup = function () use ($systemGroupList) {
  689. $menus = [];
  690. foreach ($systemGroupList as $menu) {
  691. $menus[] = ['value' => $menu['id'], 'label' => $menu['group_name']];
  692. }
  693. return $menus;
  694. };
  695. $f[] = Form::select('group_id', '用户分组', '')->setOptions(FormBuilder::setOptions($setOptionGroup))->filterable(true);
  696. $systemLabelList = app()->make(UserLabelServices::class)->getLabelList();
  697. $setOptionLabel = function () use ($systemLabelList) {
  698. $menus = [];
  699. foreach ($systemLabelList as $menu) {
  700. $menus[] = ['value' => $menu['id'], 'label' => $menu['label_name']];
  701. }
  702. return $menus;
  703. };
  704. $f[] = Form::select('label_id', '用户标签', '')->setOptions(FormBuilder::setOptions($setOptionLabel))->filterable(true)->multiple(true);
  705. $f[] = Form::radio('spread_open', '推广资格', 1)->info('禁用用户的推广资格后,在任何分销模式下该用户都无分销权限')->options([['value' => 1, 'label' => '启用'], ['value' => 0, 'label' => '禁用']]);
  706. //分销模式 人人分销
  707. $storeBrokerageStatus = sys_config('store_brokerage_statu', 1);
  708. if ($storeBrokerageStatus == 1) {
  709. $f[] = Form::radio('is_promoter', '推广员权限', 0)->info('指定分销模式下,开启或关闭用户的推广权限')->options([['value' => 1, 'label' => '开启'], ['value' => 0, 'label' => '关闭']]);
  710. }
  711. $f[] = Form::radio('status', '用户状态', 1)->options([['value' => 1, 'label' => '开启'], ['value' => 0, 'label' => '锁定']]);
  712. return create_form('添加用户', $f, $this->url('/user/user'), 'POST');
  713. }
  714. /**
  715. * 修改提交处理
  716. * @param $id
  717. * @return mixed
  718. */
  719. public function updateInfo(int $id, array $data)
  720. {
  721. $user = $this->getUserInfo($id);
  722. if (!$user) {
  723. throw new AdminException('数据不存在!');
  724. }
  725. $res1 = false;
  726. $res2 = false;
  727. $edit = array();
  728. if ($data['money_status'] && $data['money']) {//余额增加或者减少
  729. /** @var UserMoneyServices $userMoneyServices */
  730. $userMoneyServices = app()->make(UserMoneyServices::class);
  731. if ($data['money_status'] == 1) {//增加
  732. $edit['now_money'] = bcadd($user['now_money'], $data['money'], 2);
  733. $res1 = $userMoneyServices->income('system_add', $user['uid'], $data['money'], $edit['now_money'], $data['adminId'] ?? 0);
  734. } else if ($data['money_status'] == 2) {//减少
  735. if ($user['now_money'] > $data['money']) {
  736. $edit['now_money'] = bcsub($user['now_money'], $data['money'], 2);
  737. } else {
  738. $edit['now_money'] = 0;
  739. $data['money'] = $user['now_money'];
  740. }
  741. $res1 = $userMoneyServices->income('system_sub', $user['uid'], $data['money'], $edit['now_money'], $data['adminId'] ?? 0);
  742. }
  743. } else {
  744. $res1 = true;
  745. }
  746. if ($data['integration_status'] && $data['integration']) {//积分增加或者减少
  747. /** @var UserBillServices $userBill */
  748. $userBill = app()->make(UserBillServices::class);
  749. $integral_data = ['link_id' => $data['adminId'] ?? 0, 'number' => $data['integration']];
  750. if ($data['integration_status'] == 1) {//增加
  751. $edit['integral'] = bcadd($user['integral'], $data['integration'], 2);
  752. $integral_data['balance'] = $edit['integral'];
  753. $integral_data['title'] = '系统增加积分';
  754. $integral_data['mark'] = '系统增加了' . floatval($data['integration']) . '积分';
  755. $res2 = $userBill->incomeIntegral($user['uid'], 'system_add', $integral_data);
  756. } else if ($data['integration_status'] == 2) {//减少
  757. $edit['integral'] = bcsub($user['integral'], $data['integration'], 2);
  758. $integral_data['balance'] = $edit['integral'];
  759. $integral_data['title'] = '系统减少积分';
  760. $integral_data['mark'] = '系统扣除了' . floatval($data['integration']) . '积分';
  761. $res2 = $userBill->expendIntegral($user['uid'], 'system_sub', $integral_data);
  762. }
  763. } else {
  764. $res2 = true;
  765. }
  766. //修改基本信息
  767. if (!isset($data['is_other']) || !$data['is_other']) {
  768. app()->make(UserLabelRelationServices::class)->setUserLable([$id], $data['label_id']);
  769. if (isset($data['pwd']) && $data['pwd'] && $data['pwd'] != $user['pwd']) {
  770. $edit['pwd'] = $data['pwd'];
  771. }
  772. if (isset($data['spread_open'])) {
  773. $edit['spread_open'] = $data['spread_open'];
  774. }
  775. $edit['status'] = $data['status'];
  776. $edit['real_name'] = $data['real_name'];
  777. $edit['card_id'] = $data['card_id'];
  778. $edit['birthday'] = strtotime($data['birthday']);
  779. $edit['mark'] = $data['mark'];
  780. $edit['is_promoter'] = $data['is_promoter'];
  781. $edit['level'] = $data['level'];
  782. $edit['phone'] = $data['phone'];
  783. $edit['addres'] = $data['addres'];
  784. $edit['group_id'] = $data['group_id'];
  785. if ($user['level'] != $data['level']) {
  786. /** @var UserLevelServices $userLevelService */
  787. $userLevelService = app()->make(UserLevelServices::class);
  788. $userLevelService->setUserLevel((int)$user['uid'], (int)$data['level']);
  789. }
  790. }
  791. if ($edit) $res3 = $this->dao->update($id, $edit);
  792. else $res3 = true;
  793. if ($res1 && $res2 && $res3)
  794. return true;
  795. else throw new AdminException('修改失败');
  796. }
  797. /**
  798. * 编辑其他
  799. * @param $id
  800. * @return mixed
  801. * @throws \FormBuilder\Exception\FormBuilderException
  802. */
  803. public function editOther($id)
  804. {
  805. $user = $this->getUserInfo($id);
  806. if (!$user) {
  807. throw new AdminException('数据不存在!');
  808. }
  809. $f = array();
  810. $f[] = Form::radio('money_status', '修改余额', 1)->options([['value' => 1, 'label' => '增加'], ['value' => 2, 'label' => '减少']]);
  811. $f[] = Form::number('money', '余额', 0)->min(0)->max(999999.99);
  812. $f[] = Form::radio('integration_status', '修改积分', 1)->options([['value' => 1, 'label' => '增加'], ['value' => 2, 'label' => '减少']]);
  813. $f[] = Form::number('integration', '积分', 0)->min(0)->precision(0)->max(999999);
  814. return create_form('修改其他', $f, Url::buildUrl('/user/update_other/' . $id), 'PUT');
  815. }
  816. /**
  817. * 设置会员分组
  818. * @param $id
  819. * @return mixed
  820. */
  821. public function setGroup($uids)
  822. {
  823. $userGroup = app()->make(UserGroupServices::class)->getGroupList();
  824. if (count($uids) == 1) {
  825. $user = $this->getUserInfo($uids[0], ['group_id']);
  826. $setOptionUserGroup = function () use ($userGroup) {
  827. $menus = [];
  828. foreach ($userGroup as $menu) {
  829. $menus[] = ['value' => $menu['id'], 'label' => $menu['group_name']];
  830. }
  831. return $menus;
  832. };
  833. $field[] = Form::select('group_id', '用户分组', $user->getData('group_id'))->setOptions(FormBuilder::setOptions($setOptionUserGroup))->filterable(true);
  834. } else {
  835. $setOptionUserGroup = function () use ($userGroup) {
  836. $menus = [];
  837. foreach ($userGroup as $menu) {
  838. $menus[] = ['value' => $menu['id'], 'label' => $menu['group_name']];
  839. }
  840. return $menus;
  841. };
  842. $field[] = Form::select('group_id', '用户分组')->setOptions(FormBuilder::setOptions($setOptionUserGroup))->filterable(true);
  843. }
  844. $field[] = Form::hidden('uids', implode(',', $uids));
  845. return create_form('设置用户分组', $field, Url::buildUrl('/user/save_set_group'), 'PUT');
  846. }
  847. /**
  848. * 保存会员分组
  849. * @param $id
  850. * @return mixed
  851. */
  852. public function saveSetGroup($uids, int $group_id)
  853. {
  854. /** @var UserGroupServices $userGroup */
  855. $userGroup = app()->make(UserGroupServices::class);
  856. if (!$userGroup->getGroup($group_id)) {
  857. throw new AdminException('该分组不存在');
  858. }
  859. if (!$this->setUserGroup($uids, $group_id)) {
  860. throw new AdminException('设置分组失败或无改动');
  861. }
  862. return true;
  863. }
  864. /**
  865. * 设置用户标签
  866. * @param $uids
  867. * @return mixed
  868. */
  869. public function setLabel($uids)
  870. {
  871. $userLabel = app()->make(UserLabelServices::class)->getLabelList();
  872. if (count($uids) == 1) {
  873. $lids = app()->make(UserLabelRelationServices::class)->getUserLabels($uids[0]);
  874. $setOptionUserLabel = function () use ($userLabel) {
  875. $menus = [];
  876. foreach ($userLabel as $menu) {
  877. $menus[] = ['value' => $menu['id'], 'label' => $menu['label_name']];
  878. }
  879. return $menus;
  880. };
  881. $field[] = Form::select('label_id', '用户标签', $lids)->setOptions(FormBuilder::setOptions($setOptionUserLabel))->filterable(true)->multiple(true);
  882. } else {
  883. $setOptionUserLabel = function () use ($userLabel) {
  884. $menus = [];
  885. foreach ($userLabel as $menu) {
  886. $menus[] = ['value' => $menu['id'], 'label' => $menu['label_name']];
  887. }
  888. return $menus;
  889. };
  890. $field[] = Form::select('label_id', '用户标签')->setOptions(FormBuilder::setOptions($setOptionUserLabel))->filterable(true)->multiple(true);
  891. }
  892. $field[] = Form::hidden('uids', implode(',', $uids));
  893. return create_form('设置用户标签', $field, Url::buildUrl('/user/save_set_label'), 'PUT');
  894. }
  895. /**
  896. * 保存用户标签
  897. * @return mixed
  898. */
  899. public function saveSetLabel($uids, $lable_id)
  900. {
  901. foreach ($lable_id as $id) {
  902. if (!app()->make(UserLabelServices::class)->getLable((int)$id)) {
  903. throw new AdminException('有标签不存在或被删除');
  904. }
  905. }
  906. /** @var UserLabelRelationServices $services */
  907. $services = app()->make(UserLabelRelationServices::class);
  908. if (!$services->setUserLable($uids, $lable_id)) {
  909. throw new AdminException('设置标签失败');
  910. }
  911. return true;
  912. }
  913. /**
  914. * 赠送会员等级
  915. * @param int $uid
  916. * @return mixed
  917. * */
  918. public function giveLevel($id)
  919. {
  920. if (!$this->getUserInfo($id)) {
  921. throw new AdminException('用户不存在');
  922. }
  923. //查询高于当前会员的所有会员等级
  924. $grade = app()->make(UserLevelServices::class)->getUerLevelInfoByUid($id, 'grade');
  925. $systemLevelList = app()->make(SystemUserLevelServices::class)->getWhereLevelList(['grade', '>', $grade ?? 0], 'id,name');
  926. $setOptionlevel = function () use ($systemLevelList) {
  927. $menus = [];
  928. foreach ($systemLevelList as $menu) {
  929. $menus[] = ['value' => $menu['id'], 'label' => $menu['name']];
  930. }
  931. return $menus;
  932. };
  933. $field[] = Form::select('level_id', '用户等级')->setOptions(FormBuilder::setOptions($setOptionlevel))->filterable(true);
  934. return create_form('赠送等级', $field, Url::buildUrl('/user/save_give_level/' . $id), 'PUT');
  935. }
  936. /**
  937. * 执行赠送会员等级
  938. * @param int $uid
  939. * @return mixed
  940. * */
  941. public function saveGiveLevel(int $id, int $level_id)
  942. {
  943. if (!$this->getUserInfo($id)) {
  944. throw new AdminException('用户不存在');
  945. }
  946. /** @var SystemUserLevelServices $systemLevelServices */
  947. $systemLevelServices = app()->make(SystemUserLevelServices::class);
  948. /** @var UserLevelServices $userLevelServices */
  949. $userLevelServices = app()->make(UserLevelServices::class);
  950. //查询当前选择的会员等级
  951. $systemLevel = $systemLevelServices->getLevel($level_id);
  952. if (!$systemLevel) throw new AdminException('您选择赠送的用户等级不存在!');
  953. //检查是否拥有此会员等级
  954. $level = $userLevelServices->getWhereLevel(['uid' => $id, 'level_id' => $level_id], 'valid_time,is_forever');
  955. if ($level && $level['status'] == 1 && $level['is_del'] == 0) {
  956. throw new AdminException('此用户已有该用户等级,无法再次赠送');
  957. }
  958. //保存会员信息
  959. if (!$userLevelServices->setUserLevel($id, $level_id, $systemLevel)) {
  960. throw new AdminException('赠送失败');
  961. }
  962. return true;
  963. }
  964. /**
  965. * 赠送付费会员时长
  966. * @param int $uid
  967. * @return mixed
  968. * */
  969. public function giveLevelTime($id)
  970. {
  971. if (!$this->getUserInfo($id)) {
  972. throw new AdminException('用户不存在');
  973. }
  974. $field[] = Form::number('days', '增加时长(天)')->precision(0)->style(['width' => '200px'])->required();
  975. return create_form('赠送付费会员时长', $field, Url::buildUrl('/user/save_give_level_time/' . $id), 'PUT');
  976. }
  977. /**
  978. * 执行赠送付费会员时长
  979. * @param int $uid
  980. * @return mixed
  981. * */
  982. public function saveGiveLevelTime(int $id, int $days)
  983. {
  984. $userInfo = $this->getUserInfo($id);
  985. if (!$userInfo) {
  986. throw new AdminException('用户不存在');
  987. }
  988. if ($days == 0) throw new AdminException('赠送天数不能为0');
  989. if ($days < -1) throw new AdminException('天数输入错误');
  990. if ($userInfo->is_money_level == 0) {
  991. $userInfo->is_money_level = 3;
  992. if ($days == -1) {
  993. $userInfo->is_ever_level = 1;
  994. $time = 0;
  995. } else {
  996. $userInfo->overdue_time = $time = time() + ($days * 86400);
  997. }
  998. } else {
  999. if ($days == -1) {
  1000. $userInfo->is_ever_level = 1;
  1001. $time = 0;
  1002. } else {
  1003. $userInfo->overdue_time = $time = $userInfo->overdue_time + ($days * 86400);
  1004. }
  1005. }
  1006. $userInfo->save();
  1007. /** @var StoreOrderCreateServices $storeOrderCreateService */
  1008. $storeOrderCreateService = app()->make(StoreOrderCreateServices::class);
  1009. $orderInfo = [
  1010. 'uid' => $id,
  1011. 'order_id' => $storeOrderCreateService->getNewOrderId(),
  1012. 'type' => 3,
  1013. 'member_type' => 0,
  1014. 'pay_type' => 'admin',
  1015. 'paid' => 1,
  1016. 'pay_time' => time(),
  1017. 'is_free' => 1,
  1018. 'overdue_time' => $time,
  1019. 'vip_day' => $days,
  1020. 'add_time' => time()
  1021. ];
  1022. /** @var OtherOrderServices $otherOrder */
  1023. $otherOrder = app()->make(OtherOrderServices::class);
  1024. $otherOrder->save($orderInfo);
  1025. return true;
  1026. }
  1027. /**
  1028. * 清除会员等级
  1029. * @paran int $uid
  1030. * @paran boolean
  1031. * */
  1032. public function cleanUpLevel($uid)
  1033. {
  1034. if (!$this->getUserInfo($uid))
  1035. throw new AdminException('用户不存在');
  1036. /** @var UserLevelServices $services */
  1037. $services = app()->make(UserLevelServices::class);
  1038. return $this->transaction(function () use ($uid, $services) {
  1039. $res = $services->delUserLevel($uid);
  1040. $res1 = $this->dao->update($uid, ['clean_time' => time(), 'level' => 0, 'exp' => 0], 'uid');
  1041. if (!$res && !$res1)
  1042. throw new AdminException('清除失败');
  1043. return true;
  1044. });
  1045. }
  1046. /**
  1047. * 用户详细信息
  1048. * @param $uid
  1049. */
  1050. public function getUserDetailed(int $uid, $userIfno = [])
  1051. {
  1052. /** @var UserAddressServices $userAddress */
  1053. $userAddress = app()->make(UserAddressServices::class);
  1054. $field = 'real_name,phone,province,city,district,detail,post_code';
  1055. $address = $userAddress->getUserDefaultAddress($uid, $field);
  1056. if (!$address) {
  1057. $address = $userAddress->getUserAddressList($uid, $field);
  1058. $address = $address[0] ?? [];
  1059. }
  1060. $userInfo = $this->getUserInfo($uid);
  1061. return [
  1062. ['name' => '默认收货地址', 'value' => $address ? '收货人:' . $address['real_name'] . '邮编:' . $address['post_code'] . ' 收货人电话:' . $address['phone'] . ' 地址:' . $address['province'] . ' ' . $address['city'] . ' ' . $address['district'] . ' ' . $address['detail'] : ''],
  1063. ['name' => '手机号码', 'value' => $userInfo['phone']],
  1064. ['name' => '姓名', 'value' => ''],
  1065. ['name' => '微信昵称', 'value' => $userInfo['nickname']],
  1066. ['name' => '头像', 'value' => $userInfo['avatar']],
  1067. ['name' => '邮箱', 'value' => ''],
  1068. ['name' => '生日', 'value' => ''],
  1069. ['name' => '积分', 'value' => $userInfo['integral']],
  1070. ['name' => '上级推广人', 'value' => $userInfo['spread_uid'] ? $this->getUserInfo($userInfo['spread_uid'], ['nickname'])['nickname'] ?? '' : ''],
  1071. ['name' => '账户余额', 'value' => $userInfo['now_money']],
  1072. ['name' => '佣金总收入', 'value' => app()->make(UserBillServices::class)->getBrokerageSum($uid)],
  1073. ['name' => '提现总金额', 'value' => app()->make(UserExtractServices::class)->getUserExtract($uid)],
  1074. ];
  1075. }
  1076. /**
  1077. * 获取用户详情里面的用户消费能力和用户余额积分等
  1078. * @param $uid
  1079. * @return array[]
  1080. */
  1081. public function getHeaderList(int $uid, $userInfo = [])
  1082. {
  1083. if (!$userInfo) {
  1084. $userInfo = $this->getUserInfo($uid);
  1085. }
  1086. /** @var StoreOrderServices $orderServices */
  1087. $orderServices = app()->make(StoreOrderServices::class);
  1088. $where = ['uid' => $uid, 'paid' => 1, 'refund_status' => 0, 'pid' => 0];
  1089. return [
  1090. [
  1091. 'title' => '余额',
  1092. 'value' => $userInfo['now_money'] ?? 0,
  1093. 'key' => '元',
  1094. ],
  1095. [
  1096. 'title' => '总计订单',
  1097. 'value' => $orderServices->count($where),
  1098. 'key' => '笔',
  1099. ],
  1100. [
  1101. 'title' => '总消费金额',
  1102. 'value' => $orderServices->together($where, 'pay_price'),
  1103. 'key' => '元',
  1104. ],
  1105. [
  1106. 'title' => '积分',
  1107. 'value' => $userInfo['integral'] ?? 0,
  1108. 'key' => '',
  1109. ],
  1110. [
  1111. 'title' => '本月订单',
  1112. 'value' => $orderServices->count($where + ['time' => 'month']),
  1113. 'key' => '笔',
  1114. ],
  1115. [
  1116. 'title' => '本月消费金额',
  1117. 'value' => $orderServices->together($where + ['time' => 'month'], 'pay_price'),
  1118. 'key' => '元',
  1119. ]
  1120. ];
  1121. }
  1122. /**
  1123. * 获取用户记录里的积分总数和签到总数和余额变动总数
  1124. * @param $uid
  1125. * @return array
  1126. */
  1127. public function getUserBillCountData($uid)
  1128. {
  1129. /** @var UserBillServices $userBill */
  1130. $userBill = app()->make(UserBillServices::class);
  1131. $integral_count = $userBill->getIntegralCount($uid);
  1132. $sign_count = $userBill->getSignCount($uid);
  1133. $balanceChang_count = $userBill->getBrokerageCount($uid);
  1134. return [$integral_count, $sign_count, $balanceChang_count];
  1135. }
  1136. public function read(int $uid)
  1137. {
  1138. $userInfo = $this->getUserInfo($uid);
  1139. if (!$userInfo) {
  1140. throw new AdminException('数据不存在');
  1141. }
  1142. $info = [
  1143. 'uid' => $uid,
  1144. 'userinfo' => $this->getUserDetailed($uid, $userInfo),
  1145. 'headerList' => $this->getHeaderList($uid, $userInfo),
  1146. 'count' => $this->getUserBillCountData($uid),
  1147. 'ps_info' => $userInfo
  1148. ];
  1149. return $info;
  1150. }
  1151. /**
  1152. * 获取好友
  1153. * @param int $id
  1154. * @param string $field
  1155. * @return array
  1156. * @throws \think\db\exception\DataNotFoundException
  1157. * @throws \think\db\exception\DbException
  1158. * @throws \think\db\exception\ModelNotFoundException
  1159. */
  1160. public function getFriendList(int $id, string $field = 'uid,nickname,level,add_time,spread_time')
  1161. {
  1162. [$page, $limit] = $this->getPageValue();
  1163. $list = $this->dao->getList(['spread_uid' => $id], $field, $page, $limit);
  1164. /** @var SystemUserLevelServices $systemLevelServices */
  1165. $systemLevelServices = app()->make(SystemUserLevelServices::class);
  1166. $systemLevelList = $systemLevelServices->getWhereLevelList([], 'id,name');
  1167. if ($systemLevelServices) $systemLevelServices = array_combine(array_column($systemLevelList, 'id'), $systemLevelList);
  1168. foreach ($list as &$item) {
  1169. $item['type'] = $systemLevelServices[$item['level']]['name'] ?? '暂无';
  1170. $item['add_time'] = $item['spread_time'] && is_numeric($item['spread_time']) ? date('Y-m-d H:i:s', $item['spread_time']) : '';
  1171. }
  1172. $count = $this->dao->count(['spread_uid' => $id]);
  1173. return compact('list', 'count');
  1174. }
  1175. /**
  1176. * 获取单个用户信息
  1177. * @param $id 用户id
  1178. * @return mixed
  1179. */
  1180. public function oneUserInfo(int $id, string $type)
  1181. {
  1182. switch ($type) {
  1183. case 'spread':
  1184. // /** @var UserFriendsServices $services */
  1185. // $services = app()->make(UserFriendsServices::class);
  1186. // return $services->getFriendList(['uid' => $id], ['level', 'nickname']);
  1187. return $this->getFriendList($id);
  1188. case 'order':
  1189. /** @var StoreOrderServices $services */
  1190. $services = app()->make(StoreOrderServices::class);
  1191. return $services->getUserOrderList($id);
  1192. case 'integral':
  1193. /** @var UserBillServices $services */
  1194. $services = app()->make(UserBillServices::class);
  1195. return $services->getIntegralList($id, [], 'title,number,balance,mark,add_time,frozen_time');
  1196. case 'sign':
  1197. /** @var UserBillServices $services */
  1198. $services = app()->make(UserBillServices::class);
  1199. return $services->getSignList($id, [], 'title,number,mark,add_time');
  1200. case 'coupon':
  1201. /** @var StoreCouponUserServices $services */
  1202. $services = app()->make(StoreCouponUserServices::class);
  1203. return $services->getUserCouponList($id);
  1204. case 'balance_change':
  1205. /** @var UserMoneyServices $services */
  1206. $services = app()->make(UserMoneyServices::class);
  1207. return $services->balanceList(['uid' => $id]);
  1208. default:
  1209. throw new AdminException('type参数错误');
  1210. }
  1211. }
  1212. /**获取特定时间用户访问量
  1213. * @param $time
  1214. * @param $week
  1215. * @return int
  1216. */
  1217. public function todayLastVisits($time, $week)
  1218. {
  1219. return $this->dao->todayLastVisit($time, $week);
  1220. }
  1221. /**获取特定时间新增用户
  1222. * @param $time
  1223. * @param $week
  1224. * @return int
  1225. */
  1226. public function todayAddVisits($time, $week)
  1227. {
  1228. return $this->dao->todayAddVisit($time, $week);
  1229. }
  1230. /**
  1231. * 用户图表
  1232. */
  1233. public function userChart()
  1234. {
  1235. $starday = date('Y-m-d', strtotime('-30 day'));
  1236. $yesterday = date('Y-m-d', strtotime('+1 day'));
  1237. $user_list = $this->dao->userList($starday, $yesterday);
  1238. $chartdata = [];
  1239. $data = [];
  1240. $chartdata['legend'] = ['用户数'];//分类
  1241. $chartdata['yAxis']['maxnum'] = 0;//最大值数量
  1242. $chartdata['xAxis'] = [date('m-d')];//X轴值
  1243. $chartdata['series'] = [0];//分类1值
  1244. if (!empty($user_list)) {
  1245. foreach ($user_list as $k => $v) {
  1246. $data['day'][] = $v['day'];
  1247. $data['count'][] = $v['count'];
  1248. if ($chartdata['yAxis']['maxnum'] < $v['count'])
  1249. $chartdata['yAxis']['maxnum'] = $v['count'];
  1250. }
  1251. $chartdata['xAxis'] = $data['day'];//X轴值
  1252. $chartdata['series'] = $data['count'];//分类1值
  1253. }
  1254. $chartdata['bing_xdata'] = ['未消费用户', '消费一次用户', '留存客户', '回流客户'];
  1255. $color = ['#5cadff', '#b37feb', '#19be6b', '#ff9900'];
  1256. $pay[0] = $this->dao->count(['pay_count' => 0]);
  1257. $pay[1] = $this->dao->count(['pay_count' => 1]);
  1258. $pay[2] = $this->dao->userCount(1);
  1259. $pay[3] = $this->dao->userCount(2);
  1260. foreach ($pay as $key => $item) {
  1261. $bing_data[] = ['name' => $chartdata['bing_xdata'][$key], 'value' => $pay[$key], 'itemStyle' => ['color' => $color[$key]]];
  1262. }
  1263. $chartdata['bing_data'] = $bing_data;
  1264. return $chartdata;
  1265. }
  1266. /***********************************************/
  1267. /************ 前端api services *****************/
  1268. /***********************************************/
  1269. /**
  1270. * 用户信息
  1271. * @param $info
  1272. * @return mixed
  1273. */
  1274. public function userInfo($info)
  1275. {
  1276. /** @var UserBillServices $userBill */
  1277. $userBill = app()->make(UserBillServices::class);
  1278. $uid = (int)$info['uid'];
  1279. $broken_time = intval(sys_config('extract_time'));
  1280. $search_time = time() - 86400 * $broken_time;
  1281. //改造时间
  1282. $search_time = '1970/01/01' . ' - ' . date('Y/m/d H:i:s', $search_time);
  1283. //可提现佣金
  1284. //返佣 +
  1285. $brokerage_commission = (string)$userBill->getUsersBokerageSum(['uid' => $uid, 'pm' => 1], $search_time);
  1286. //退款退的佣金 -
  1287. $refund_commission = (string)$userBill->getUsersBokerageSum(['uid' => $uid, 'pm' => 0], $search_time);
  1288. $info['broken_commission'] = bcsub($brokerage_commission, $refund_commission, 2);
  1289. if ($info['broken_commission'] < 0)
  1290. $info['broken_commission'] = 0;
  1291. $info['commissionCount'] = bcsub($info['brokerage_price'], $info['broken_commission'], 2);
  1292. if ($info['commissionCount'] < 0)
  1293. $info['commissionCount'] = 0;
  1294. return $info;
  1295. }
  1296. /**
  1297. * 个人中心
  1298. * @param array $user
  1299. */
  1300. public function personalHome(array $user, $tokenData)
  1301. {
  1302. $userInfo = $user;
  1303. $uid = (int)$user['uid'];
  1304. /** @var StoreCouponUserServices $storeCoupon */
  1305. $storeCoupon = app()->make(StoreCouponUserServices::class);
  1306. /** @var UserBillServices $userBill */
  1307. $userBill = app()->make(UserBillServices::class);
  1308. /** @var UserExtractServices $userExtract */
  1309. $userExtract = app()->make(UserExtractServices::class);
  1310. /** @var StoreOrderServices $storeOrder */
  1311. $storeOrder = app()->make(StoreOrderServices::class);
  1312. /** @var UserLevelServices $userLevel */
  1313. $userLevel = app()->make(UserLevelServices::class);
  1314. /** @var StoreServiceServices $storeService */
  1315. $storeService = app()->make(StoreServiceServices::class);
  1316. /** @var WechatUserServices $wechatUser */
  1317. $wechatUser = app()->make(WechatUserServices::class);
  1318. /** @var UserInvoiceServices $userInvoice */
  1319. $userInvoice = app()->make(UserInvoiceServices::class);
  1320. /** @var MemberCardServices $memberCardService */
  1321. $memberCardService = app()->make(MemberCardServices::class);
  1322. /** @var StoreProductRelationServices $collect */
  1323. $collect = app()->make(StoreProductRelationServices::class);
  1324. /** @var MessageSystemServices $messageSystemServices */
  1325. $messageSystemServices = app()->make(MessageSystemServices::class);
  1326. /** @var DiyServices $diyServices */
  1327. $diyServices = app()->make(DiyServices::class);
  1328. /** @var AgentLevelServices $agentLevelServices */
  1329. $agentLevelServices = app()->make(AgentLevelServices::class);
  1330. //看付费会员是否开启
  1331. $isOpenMember = $memberCardService->isOpenMemberCard();
  1332. $user['is_open_member'] = $isOpenMember;
  1333. $user['agent_level_name'] = '';
  1334. if ($user['agent_level']) {
  1335. $levelInfo = $agentLevelServices->getLevelInfo((int)$user['agent_level'], 'id,name');
  1336. $user['agent_level_name'] = $levelInfo && $levelInfo['name'] ? $levelInfo['name'] : '';
  1337. }
  1338. //会员领取优惠券
  1339. // $couponService->sendMemberCoupon($uid);
  1340. //看是否会员过期
  1341. $this->offMemberLevel($uid, $userInfo);
  1342. $wechatUserInfo = $wechatUser->getOne(['uid' => $uid, 'user_type' => $tokenData['type']]);
  1343. $user['is_complete'] = $wechatUserInfo['is_complete'] ?? 0;
  1344. $user['couponCount'] = $storeCoupon->getUserValidCouponCount((int)$uid);
  1345. $user['like'] = app()->make(StoreProductRelationServices::class)->getUserCollectCount($user['uid']);
  1346. $user['orderStatusNum'] = $storeOrder->getOrderData($uid, true, true);
  1347. $user['notice'] = 0;
  1348. /** @var UserMoneyServices $userMoney */
  1349. $userMoney = app()->make(UserMoneyServices::class);
  1350. $user['recharge'] = $userMoney->sum([
  1351. ['uid', '=', $uid], ['pm', '=', 1], ['type', 'in', ['recharge', 'system_add', 'extract']]
  1352. ], 'number');
  1353. $user['orderStatusSum'] = bcsub((string)$user['recharge'], (string)$user['now_money'], 2);
  1354. $user['extractTotalPrice'] = $userExtract->getExtractSum(['uid' => $uid, 'status' => 1]);//累计提现
  1355. $user['extractPrice'] = $user['brokerage_price'];//可提现
  1356. $user['statu'] = (int)sys_config('store_brokerage_statu');
  1357. if (!$user['is_promoter'] && $user['statu'] == 2) {
  1358. $price = $storeOrder->sum(['paid' => 1, 'refund_status' => 0, 'uid' => $user['uid']], 'pay_price');
  1359. $status = is_brokerage_statu($price);
  1360. if ($status) {
  1361. $this->dao->update($uid, ['is_promoter' => 1], 'uid');
  1362. $user['is_promoter'] = 1;
  1363. } else {
  1364. $storeBrokeragePrice = sys_config('store_brokerage_price', 0);
  1365. $user['promoter_price'] = bcsub((string)$storeBrokeragePrice, (string)$price, 2);
  1366. }
  1367. }
  1368. /** @var UserBrokerageServices $frozenPrices */
  1369. $frozenPrices = app()->make(UserBrokerageServices::class);
  1370. $user['broken_commission'] = $frozenPrices->getUserFrozenPrice($uid);
  1371. if ($user['broken_commission'] < 0)
  1372. $user['broken_commission'] = 0;
  1373. $user['commissionCount'] = bcsub((string)$user['brokerage_price'], (string)$user['broken_commission'], 2);
  1374. if ($user['commissionCount'] < 0)
  1375. $user['commissionCount'] = 0;
  1376. if (!sys_config('member_func_status'))
  1377. $user['vip'] = false;
  1378. else {
  1379. $userLevel = $userLevel->getUerLevelInfoByUid($user['uid']);
  1380. $user['vip'] = (bool)$userLevel;
  1381. if ($user['vip']) {
  1382. $user['vip_id'] = $userLevel['id'] ?? 0;
  1383. $user['vip_icon'] = $userLevel['icon'] ?? '';
  1384. $user['vip_name'] = $userLevel['name'] ?? '';
  1385. }
  1386. }
  1387. $user['yesterDay'] = $userBill->getUsersBokerageSum(['uid' => $uid, 'pm' => 1], 'yesterday');
  1388. $user['recharge_switch'] = (int)sys_config('recharge_switch');//充值开关
  1389. $user['adminid'] = $storeService->checkoutIsService(['uid' => $uid, 'status' => 1, 'customer' => 1]);
  1390. if ($user['phone'] && $user['user_type'] != 'h5') {
  1391. $user['switchUserInfo'][] = $userInfo;
  1392. $h5UserInfo = $this->dao->getOne(['account' => $user['phone'], 'user_type' => 'h5']);
  1393. if ($h5UserInfo) {
  1394. $user['switchUserInfo'][] = $h5UserInfo;
  1395. }
  1396. } else if ($user['phone'] && $user['user_type'] == 'h5') {
  1397. $wechatUserInfo = $this->getOne([['phone', '=', $user['phone']], ['user_type', '<>', 'h5']]);
  1398. if ($wechatUserInfo) {
  1399. $user['switchUserInfo'][] = $wechatUserInfo;
  1400. }
  1401. $user['switchUserInfo'][] = $userInfo;
  1402. } else if (!$user['phone']) {
  1403. $user['switchUserInfo'][] = $userInfo;
  1404. }
  1405. $user['broken_day'] = (int)sys_config('extract_time');//佣金冻结时间
  1406. $user['balance_func_status'] = (int)sys_config('balance_func_status', 0);
  1407. $invoice_func = $userInvoice->invoiceFuncStatus();
  1408. $user['invioce_func'] = $invoice_func['invoice_func'];
  1409. $user['special_invoice'] = $invoice_func['special_invoice'];
  1410. $user['collectCount'] = $collect->count(['uid' => $uid]);
  1411. $user['spread_status'] = $this->checkUserPromoter($user['uid']);
  1412. $user['pay_vip_status'] = $user['is_ever_level'] || ($user['is_money_level'] && $user['overdue_time'] > time());
  1413. $user['member_style'] = (int)$diyServices->getColorChange('member');
  1414. if ($user['is_ever_level']) {
  1415. $user['vip_status'] = 1;//永久会员
  1416. } else {
  1417. if (!$user['is_money_level'] && $user['overdue_time'] && $user['overdue_time'] < time()) {
  1418. $user['vip_status'] = -1;//开通过已过期
  1419. } else if (!$user['overdue_time'] && !$user['is_money_level']) {
  1420. $user['vip_status'] = 2;//没有开通过
  1421. } else if ($user['is_money_level'] && $user['overdue_time'] && $user['overdue_time'] > time()) {
  1422. $user['vip_status'] = 3;//开通了,没有到期
  1423. }
  1424. }
  1425. $user['svip_open'] = (bool)sys_config('member_card_status');
  1426. /** @var StoreServiceRecordServices $servicesRecord */
  1427. $servicesRecord = app()->make(StoreServiceRecordServices::class);
  1428. $service_num = $servicesRecord->sum(['user_id' => $uid], 'mssage_num');
  1429. $message = $messageSystemServices->count(['uid' => $uid, 'look' => 0, 'is_del' => 0]);
  1430. $user['service_num'] = $service_num + $message;
  1431. /** @var AgentLevelServices $userSpread */
  1432. $agentLevel = app()->make(AgentLevelServices::class);
  1433. $user['spread_level_count'] = $agentLevel->count(['status' => 1, 'is_del' => 0]);
  1434. $user['extract_type'] = sys_config('extract_type');
  1435. $user['integral'] = intval($user['integral']);
  1436. $user['is_agent_level'] = $agentLevelServices->count(['status' => 1, 'is_del' => 0]) > 0 ? 1 : 0;
  1437. return $user;
  1438. }
  1439. /**
  1440. * 用户资金统计
  1441. * @param int $uid
  1442. */
  1443. public function balance(int $uid)
  1444. {
  1445. $userInfo = $this->getUserInfo($uid);
  1446. if (!$userInfo) {
  1447. throw new ValidateException('数据不存在');
  1448. }
  1449. /** @var UserBillServices $userBill */
  1450. $userBill = app()->make(UserBillServices::class);
  1451. /** @var StoreOrderServices $storeOrder */
  1452. $storeOrder = app()->make(StoreOrderServices::class);
  1453. $user['now_money'] = $userInfo['now_money'];//当前总资金
  1454. $user['recharge'] = $userBill->getRechargeSum($uid);//累计充值
  1455. $user['orderStatusSum'] = $storeOrder->sum(['uid' => $uid, 'paid' => 1, 'is_del' => 0], 'pay_price');//累计消费
  1456. return $user;
  1457. }
  1458. /**
  1459. * 用户修改信息
  1460. * @param Request $request
  1461. * @return mixed
  1462. */
  1463. public function eidtNickname(int $uid, array $data)
  1464. {
  1465. if (!$this->getUserInfo($uid)) {
  1466. throw new ValidateException('用户不存在');
  1467. }
  1468. if (!$this->dao->update($uid, $data, 'uid')) {
  1469. throw new ValidateException('修改失败');
  1470. }
  1471. return true;
  1472. }
  1473. /**
  1474. * 获取推广人排行
  1475. * @param $data 查询条件
  1476. * @return array
  1477. * @throws \think\db\exception\DataNotFoundException
  1478. * @throws \think\db\exception\ModelNotFoundException
  1479. * @throws \think\exception\DbException
  1480. */
  1481. public function getRankList(array $data)
  1482. {
  1483. $startTime = strtotime('this week Monday');
  1484. $endTime = time();
  1485. switch ($data['type']) {
  1486. case 'week':
  1487. $startTime = strtotime('this week Monday');
  1488. break;
  1489. case 'month':
  1490. $startTime = strtotime('last month');
  1491. break;
  1492. }
  1493. [$page, $limit] = $this->getPageValue();
  1494. $field = 't0.uid,t0.spread_uid,count(t1.spread_uid) AS count,t0.add_time,t0.nickname,t0.avatar';
  1495. return $this->dao->getAgentRankList([$startTime, $endTime], $field, $page, $limit);
  1496. }
  1497. /**
  1498. * 静默绑定推广人
  1499. * @param Request $request
  1500. * @return mixed
  1501. */
  1502. public function spread(int $uid, int $spreadUid, $code)
  1503. {
  1504. $userInfo = $this->getUserInfo($uid);
  1505. if (!$userInfo) {
  1506. throw new ValidateException('数据不存在');
  1507. }
  1508. if ($code && !$spreadUid) {
  1509. /** @var QrcodeServices $qrCode */
  1510. $qrCode = app()->make(QrcodeServices::class);
  1511. if ($info = $qrCode->getOne(['id' => $code, 'status' => 1])) {
  1512. $spreadUid = $info['third_id'];
  1513. }
  1514. }
  1515. $userSpreadUid = $this->dao->value(['uid' => $spreadUid], 'spread_uid');
  1516. //记录好友关系
  1517. if ($spreadUid && $uid && $spreadUid != $uid) {
  1518. /** @var UserFriendsServices $serviceFriend */
  1519. $serviceFriend = app()->make(UserFriendsServices::class);
  1520. $serviceFriend->saveFriend([
  1521. 'uid' => $uid,
  1522. 'friends_uid' => $spreadUid,
  1523. ]);
  1524. }
  1525. //记录上下级关系
  1526. if (!$userInfo['spread_uid'] && $spreadUid != $uid && $userSpreadUid != $userInfo['uid']) {
  1527. if ((sys_config('brokerage_bindind') == 2 && $userInfo['add_time'] == $userInfo['last_time']) || sys_config('brokerage_bindind') == 1) {
  1528. if (!$this->dao->update($uid, ['spread_uid' => $spreadUid, 'spread_time' => time()], 'uid')) {
  1529. throw new ValidateException('绑定推广关系失败');
  1530. }
  1531. /** @var UserBillServices $userBill */
  1532. $userBill = app()->make(UserBillServices::class);
  1533. //邀请新用户增加经验
  1534. $userBill->inviteUserIncExp((int)$spreadUid);
  1535. }
  1536. }
  1537. return true;
  1538. }
  1539. /**
  1540. * 添加访问记录
  1541. * @param Request $request
  1542. * @return mixed
  1543. */
  1544. public function setVisit(array $data)
  1545. {
  1546. $userInfo = $this->getUserInfo($data['uid']);
  1547. if (!$userInfo) {
  1548. throw new ValidateException('数据不存在');
  1549. }
  1550. $data['channel_type'] = $userInfo['user_type'];
  1551. $data['add_time'] = time();
  1552. /** @var WechatUserServices $wechatUserServices */
  1553. $wechatUserServices = app()->make(WechatUserServices::class);
  1554. $wechatUser = $wechatUserServices->get(['uid' => $userInfo['uid'], 'user_type' => $userInfo['user_type']]);
  1555. if (!$wechatUser) {
  1556. $wechatUser = $wechatUserServices->get(['uid' => $userInfo['uid']]);
  1557. }
  1558. if ($wechatUser) {
  1559. $data['province'] = $wechatUser['province'];
  1560. }
  1561. /** @var UserVisitServices $userVisit */
  1562. $userVisit = app()->make(UserVisitServices::class);
  1563. if ($userVisit->save($data)) {
  1564. return true;
  1565. } else {
  1566. throw new ValidateException('添加访问记录失败');
  1567. }
  1568. }
  1569. /**
  1570. * 获取活动状态
  1571. * @return mixed
  1572. */
  1573. public function activity()
  1574. {
  1575. /** @var StoreBargainServices $storeBragain */
  1576. $storeBragain = app()->make(StoreBargainServices::class);
  1577. /** @var StoreCombinationServices $storeCombinaion */
  1578. $storeCombinaion = app()->make(StoreCombinationServices::class);
  1579. /** @var StoreSeckillServices $storeSeckill */
  1580. $storeSeckill = app()->make(StoreSeckillServices::class);
  1581. $data['is_bargin'] = (bool)$storeBragain->validBargain();
  1582. $data['is_pink'] = (bool)$storeCombinaion->validCombination();
  1583. $data['is_seckill'] = (bool)$storeSeckill->getSeckillCount();
  1584. return $data;
  1585. }
  1586. /**
  1587. * 获取用户下级推广人
  1588. * @param int $uid 当前用户
  1589. * @param int $grade 等级 0 一级 1 二级
  1590. * @param string $orderBy 排序
  1591. * @param string $keyword
  1592. * @return array|bool
  1593. */
  1594. public function getUserSpreadGrade(int $uid = 0, $grade = 0, $orderBy = '', $keyword = '')
  1595. {
  1596. $user = $this->getUserInfo($uid);
  1597. if (!$user) {
  1598. throw new ValidateException('数据不存在');
  1599. }
  1600. $spread_one_ids = $this->getUserSpredadUids($uid, 1);
  1601. $spread_two_ids = $this->getUserSpredadUids($uid, 2);
  1602. $data = [
  1603. 'total' => count($spread_one_ids),
  1604. 'totalLevel' => count($spread_two_ids),
  1605. 'list' => []
  1606. ];
  1607. $data['count'] = $data['total'] + $data['totalLevel'];
  1608. /** @var UserStoreOrderServices $userStoreOrder */
  1609. $userStoreOrder = app()->make(UserStoreOrderServices::class);
  1610. $list = [];
  1611. if ($grade == 0) {
  1612. if ($spread_one_ids) $list = $userStoreOrder->getUserSpreadCountList($spread_one_ids, $orderBy, $keyword);
  1613. } else {
  1614. if ($spread_two_ids) $list = $userStoreOrder->getUserSpreadCountList($spread_two_ids, $orderBy, $keyword);
  1615. }
  1616. foreach ($list as &$item) {
  1617. if (isset($item['spread_time']) && $item['spread_time']) {
  1618. $item['time'] = date('Y/m/d', $item['spread_time']);
  1619. }
  1620. }
  1621. $data['list'] = $list;
  1622. return $data;
  1623. }
  1624. /**
  1625. * 获取推广人uids
  1626. * @param int $uid
  1627. * @param bool $one
  1628. * @return array
  1629. */
  1630. public function getUserSpredadUids(int $uid, int $type = 0)
  1631. {
  1632. $uids = $this->dao->getColumn(['spread_uid' => $uid], 'uid');
  1633. if ($type === 1) {
  1634. return $uids;
  1635. }
  1636. if ($uids) {
  1637. $uidsTwo = $this->dao->getColumn([['spread_uid', 'in', $uids]], 'uid');
  1638. if ($type === 2) {
  1639. return $uidsTwo;
  1640. }
  1641. if ($uidsTwo) {
  1642. $uids = array_merge($uids, $uidsTwo);
  1643. }
  1644. }
  1645. return $uids;
  1646. }
  1647. /**
  1648. * 检测用户是否是推广员
  1649. * @param int $uid
  1650. * @param $user
  1651. * @return bool
  1652. */
  1653. public function checkUserPromoter(int $uid, $user = [])
  1654. {
  1655. if (!$user) {
  1656. $user = $this->getUserInfo($uid);
  1657. }
  1658. if (!$user) {
  1659. return false;
  1660. }
  1661. //分销是否开启
  1662. if (!sys_config('brokerage_func_status')) {
  1663. return false;
  1664. }
  1665. //用户分校推广资格是否开启4.0.32
  1666. if (isset($user['spread_open']) && !$user['spread_open']) {
  1667. return false;
  1668. }
  1669. /** @var StoreOrderServices $storeOrder */
  1670. $storeOrder = app()->make(StoreOrderServices::class);
  1671. $sumPrice = $storeOrder->sum(['uid' => $uid, 'paid' => 1, 'is_del' => 0], 'pay_price');//累计消费
  1672. $store_brokerage_statu = sys_config('store_brokerage_statu');
  1673. $store_brokerage_price = sys_config('store_brokerage_price');
  1674. if ($user['is_promoter'] || $store_brokerage_statu == 2 || ($store_brokerage_statu == 3 && $sumPrice > $store_brokerage_price)) {
  1675. return true;
  1676. }
  1677. return false;
  1678. }
  1679. /**
  1680. * 同步微信粉丝用户(后台接口)
  1681. * @return bool
  1682. */
  1683. public function syncWechatUsers()
  1684. {
  1685. $appid = sys_config('wechat_appid');
  1686. $appSecret = sys_config('wechat_appsecret');
  1687. if (!$appid || !$appSecret) {
  1688. throw new AdminException('请先到设置->系统设置->应用端配置:配置微信appid、appSecret等参数');
  1689. }
  1690. $key = md5('sync_wechat_users');
  1691. //一天点击一次
  1692. if (CacheService::get($key)) {
  1693. return true;
  1694. }
  1695. $next_openid = null;
  1696. do {
  1697. $result = WechatService::getUsersList($next_openid);
  1698. $userOpenids = $result['data'];
  1699. //拆分大数组
  1700. $opemidArr = array_chunk($userOpenids, 100);
  1701. foreach ($opemidArr as $openids) {
  1702. //加入同步|更新用户队列
  1703. UserJob::dispatch([$openids]);
  1704. }
  1705. $next_openid = $result['next_openid'];
  1706. } while ($next_openid != null);
  1707. CacheService::set($key, 1, 3600 * 24);
  1708. return true;
  1709. }
  1710. /**
  1711. * 导入微信粉丝用户
  1712. * @param array $openids
  1713. * @return bool
  1714. */
  1715. public function importUser(array $noBeOpenids)
  1716. {
  1717. if (!$noBeOpenids) {
  1718. return true;
  1719. }
  1720. $dataAll = $data = [];
  1721. $time = time();
  1722. foreach ($noBeOpenids as $openid) {
  1723. try {
  1724. $info = WechatService::getUserInfo($openid);
  1725. $info = is_object($info) ? $info->toArray() : $info;
  1726. } catch (\Throwable $e) {
  1727. $info = [];
  1728. }
  1729. if (!$info) continue;
  1730. $data['nickname'] = $info['nickname'] ?? '';
  1731. $data['headimgurl'] = $info['headimgurl'] ?? '';
  1732. $userInfoData = $this->setUserInfo($data);
  1733. if (!$userInfoData) {
  1734. throw new AdminException('用户信息储存失败!');
  1735. }
  1736. $data['uid'] = $userInfoData['uid'];
  1737. $data['subscribe'] = $info['subscribe'] ?? 1;
  1738. $data['unionid'] = $info['unionid'] ?? '';
  1739. $data['openid'] = $info['openid'] ?? '';
  1740. $data['sex'] = $info['sex'] ?? 0;
  1741. $data['language'] = $info['language'] ?? '';
  1742. $data['city'] = $info['city'] ?? '';
  1743. $data['province'] = $info['province'] ?? '';
  1744. $data['country'] = $info['country'] ?? '';
  1745. $data['subscribe_time'] = $info['subscribe_time'] ?? '';
  1746. $data['groupid'] = $info['groupid'] ?? 0;
  1747. $data['remark'] = $info['remark'] ?? '';
  1748. $data['tagid_list'] = isset($info['tagid_list']) && $info['tagid_list'] ? implode(',', $info['tagid_list']) : '';
  1749. $data['add_time'] = $time;
  1750. $data['is_complete'] = 1;
  1751. $dataAll[] = $data;
  1752. }
  1753. if ($dataAll) {
  1754. /** @var WechatUserServices $wechatUser */
  1755. $wechatUser = app()->make(WechatUserServices::class);
  1756. if (!$wechatUser->saveAll($dataAll)) {
  1757. throw new ValidateException('保存用户信息失败');
  1758. }
  1759. }
  1760. return true;
  1761. }
  1762. /** 修改会员的时间及是否会员状态
  1763. * @param int $vip_day 会员天数
  1764. * @param array $user_id 用户id
  1765. * @param int $is_money_level 会员来源途径
  1766. * @param bool $member_type 会员卡类型
  1767. * @return mixed
  1768. * @throws \think\db\exception\DataNotFoundException
  1769. * @throws \think\db\exception\DbException
  1770. * @throws \think\db\exception\ModelNotFoundException
  1771. */
  1772. public function setMemberOverdueTime($vip_day, int $user_id, int $is_money_level, $member_type = false)
  1773. {
  1774. if ($vip_day == 0) throw new ValidateException('天数不能为0');
  1775. $user_info = $this->getUserInfo($user_id);
  1776. if (!$user_info) throw new ValidateException('用户数据不存在');
  1777. if (!$member_type) $member_type = "month";
  1778. if ($member_type == 'ever') {
  1779. $overdue_time = 0;
  1780. $is_ever_level = 1;
  1781. } else {
  1782. if ($user_info['is_money_level'] == 0) {
  1783. $overdue_time = bcadd(bcmul($vip_day, 86400, 0), time(), 0);
  1784. } else {
  1785. $overdue_time = bcadd(bcmul($vip_day, 86400, 0), $user_info['overdue_time'], 0);
  1786. }
  1787. $is_ever_level = 0;
  1788. }
  1789. $setData['overdue_time'] = $overdue_time;
  1790. $setData['is_ever_level'] = $is_ever_level;
  1791. $setData['is_money_level'] = $is_money_level ?: 0;
  1792. // if ($user_info['level'] == 0) $setData['level'] = 1;
  1793. return $this->dao->update(['uid' => $user_id], $setData);
  1794. }
  1795. /**
  1796. * 会员过期改变状态,变为普通会员
  1797. * @param $uid
  1798. * @param $userInfo
  1799. * @return bool
  1800. * @throws \think\db\exception\DataNotFoundException
  1801. * @throws \think\db\exception\DbException
  1802. * @throws \think\db\exception\ModelNotFoundException
  1803. */
  1804. public function offMemberLevel($uid, $userInfo = [])
  1805. {
  1806. if (!$uid) return false;
  1807. if (!$userInfo) {
  1808. $userInfo = $this->dao->get($uid);
  1809. }
  1810. if (!$userInfo) return false;
  1811. if ($userInfo['is_ever_level'] == 0 && $userInfo['is_money_level'] > 0 && $userInfo['overdue_time'] < time()) {
  1812. $this->dao->update(['uid' => $uid], ['is_money_level' => 0/*, 'overdue_time' => 0*/]);
  1813. return false;
  1814. }
  1815. return true;
  1816. }
  1817. /**
  1818. * @param array $where
  1819. * @return array
  1820. * @throws \think\db\exception\DataNotFoundException
  1821. * @throws \think\db\exception\DbException
  1822. * @throws \think\db\exception\ModelNotFoundException
  1823. */
  1824. public function getUserInfoList(array $where, $field = "*")
  1825. {
  1826. return $this->dao->getUserInfoList($where, $field);
  1827. }
  1828. /**
  1829. * 增加推广用户佣金
  1830. * @param int $uid
  1831. * @param int $spread_uid
  1832. * @param array $userInfo
  1833. * @param array $spread_user
  1834. * @return bool|mixed
  1835. * @throws \think\db\exception\DataNotFoundException
  1836. * @throws \think\db\exception\DbException
  1837. * @throws \think\db\exception\ModelNotFoundException
  1838. */
  1839. public function addBrokeragePrice(int $uid, int $spread_uid, array $userInfo = [], array $spread_user = [])
  1840. {
  1841. if (!$uid || !$spread_uid) {
  1842. return false;
  1843. }
  1844. //商城分销功能是否开启 0关闭1开启
  1845. if (!sys_config('brokerage_func_status')) return true;
  1846. if (!sys_config('brokerage_user_status')) return true;
  1847. //获取设置推广佣金单价
  1848. $brokerage_price = sys_config('uni_brokerage_price', 0);
  1849. //获取推广佣金当日限额
  1850. $day_brokerage_price_upper = sys_config('day_brokerage_price_upper', 0);
  1851. if (!floatval($brokerage_price) || !floatval($day_brokerage_price_upper)) {
  1852. return true;
  1853. }
  1854. if (!$userInfo) {
  1855. $userInfo = $this->getUserInfo($uid);
  1856. }
  1857. if (!$userInfo) {
  1858. return false;
  1859. }
  1860. if (!$spread_user) {
  1861. $spread_user = $this->dao->getOne(['uid' => $spread_uid, 'status' => 1]);
  1862. }
  1863. if (!$spread_user) {
  1864. return false;
  1865. }
  1866. if (!$this->checkUserPromoter($spread_uid, $spread_user)) {
  1867. return false;
  1868. }
  1869. /** @var UserBrokerageServices $userBrokerageServices */
  1870. $userBrokerageServices = app()->make(UserBrokerageServices::class);
  1871. // -1不限制
  1872. if ($day_brokerage_price_upper != -1) {
  1873. if ($day_brokerage_price_upper <= 0) {
  1874. return true;
  1875. } else {
  1876. //获取上级用户今日获取推广用户佣金
  1877. $spread_day_brokerage = $userBrokerageServices->getUserBrokerageSum($spread_uid, ['brokerage_user'], 'today');
  1878. //超过上限
  1879. if (($spread_day_brokerage + $brokerage_price) > $day_brokerage_price_upper) {
  1880. return true;
  1881. }
  1882. }
  1883. }
  1884. $spreadPrice = $spread_user['brokerage_price'];
  1885. // 上级推广员返佣之后的金额
  1886. $balance = bcadd($spreadPrice, $brokerage_price, 2);
  1887. return $this->transaction(function () use ($uid, $spread_uid, $brokerage_price, $userInfo, $balance, $userBrokerageServices) {
  1888. // 添加返佣记录
  1889. $res1 = $userBrokerageServices->income('get_user_brokerage', $spread_uid, [
  1890. 'nickname' => $userInfo['nickname'],
  1891. 'number' => floatval($brokerage_price)
  1892. ], $balance, $uid);
  1893. // 添加用户余额
  1894. $res2 = $this->dao->bcInc($spread_uid, 'brokerage_price', $brokerage_price, 'uid');
  1895. //给上级发送获得佣金的模板消息
  1896. /** @var StoreOrderTakeServices $storeOrderTakeServices */
  1897. $storeOrderTakeServices = app()->make(StoreOrderTakeServices::class);
  1898. $storeOrderTakeServices->sendBackOrderBrokerage([], $spread_uid, $brokerage_price, 'user');
  1899. return $res1 && $res2;
  1900. });
  1901. }
  1902. /**
  1903. * 获取上级uid
  1904. * @param int $uid
  1905. * @param array $userInfo
  1906. * @param bool $is_spread
  1907. * @return int|mixed
  1908. */
  1909. public function getSpreadUid(int $uid, $userInfo = [], $is_spread = true)
  1910. {
  1911. if (!$uid) {
  1912. return 0;
  1913. }
  1914. //商城分销功能是否开启 0关闭1开启
  1915. if (!sys_config('brokerage_func_status')) return -1;
  1916. if (!$userInfo) {
  1917. $userInfo = $this->getUserInfo($uid);
  1918. }
  1919. if (!$userInfo) {
  1920. return 0;
  1921. }
  1922. //上级的上级不需要检测自购
  1923. if ($is_spread) {
  1924. //开启自购
  1925. $is_self_brokerage = sys_config('is_self_brokerage', 0);
  1926. if ($is_self_brokerage && $is_spread) {
  1927. return $uid;
  1928. }
  1929. }
  1930. //绑定类型
  1931. $store_brokergae_binding_status = sys_config('store_brokerage_binding_status', 1);
  1932. if ($store_brokergae_binding_status == 1 || $store_brokergae_binding_status == 3) {
  1933. return $userInfo['spread_uid'];
  1934. }
  1935. //分销绑定类型为时间段且没过期
  1936. $store_brokerage_binding_time = sys_config('store_brokerage_binding_time', 30);
  1937. if ($store_brokergae_binding_status == 2 && ($userInfo['spread_time'] + $store_brokerage_binding_time * 24 * 3600) > time()) {
  1938. return $userInfo['spread_uid'];
  1939. }
  1940. return -1;
  1941. }
  1942. /**
  1943. * 获取事业部/代理/员工列表
  1944. * @param array $where
  1945. * @param string $field
  1946. * @return array
  1947. * @throws \think\db\exception\DataNotFoundException
  1948. * @throws \think\db\exception\DbException
  1949. * @throws \think\db\exception\ModelNotFoundException
  1950. */
  1951. public function getDivisionList(array $where = [], string $field = '*')
  1952. {
  1953. [$page, $limit] = $this->getPageValue();
  1954. $list = $this->dao->getList($where, $field, $page, $limit);
  1955. $count = $this->dao->count($where);
  1956. return compact('list', 'count');
  1957. }
  1958. /**
  1959. * 添加编辑用户信息时候的信息
  1960. * @param $uid
  1961. * @return array
  1962. * @throws \think\db\exception\DataNotFoundException
  1963. * @throws \think\db\exception\DbException
  1964. * @throws \think\db\exception\ModelNotFoundException
  1965. */
  1966. public function getUserSaveInfo($uid)
  1967. {
  1968. /** @var UserLabelServices $userLabelServices */
  1969. $userLabelServices = app()->make(UserLabelServices::class);
  1970. /** @var UserLabelRelationServices $userLabelRelationServices */
  1971. $userLabelRelationServices = app()->make(UserLabelRelationServices::class);
  1972. /** @var UserLabelCateServices $userLabelCateServices */
  1973. $userLabelCateServices = app()->make(UserLabelCateServices::class);
  1974. /** @var UserGroupServices $userGroupServices */
  1975. $userGroupServices = app()->make(UserGroupServices::class);
  1976. /** @var SystemUserLevelServices $systemUserLevelServices */
  1977. $systemUserLevelServices = app()->make(SystemUserLevelServices::class);
  1978. $userInfo = $this->dao->get($uid);
  1979. if ($userInfo) {
  1980. $label_ids = $userLabelRelationServices->getUserLabels($uid);
  1981. $userInfo['label_id'] = !empty($label_ids) ? $userLabelServices->getLabelList(['ids' => $label_ids], ['id', 'label_name']) : [];
  1982. $userInfo['birthday'] = date('Y-m-d', (int)$userInfo['birthday']);
  1983. }
  1984. $levelInfo = $systemUserLevelServices->getWhereLevelList([], 'id,name');
  1985. $groupInfo = $userGroupServices->getGroupList();
  1986. $labelInfo = $userLabelCateServices->getUserLabel($uid);
  1987. return compact('userInfo', 'levelInfo', 'groupInfo', 'labelInfo');
  1988. }
  1989. }