UserServices.php 84 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103
  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\kefu\service\StoreServiceRecordServices;
  23. use app\services\kefu\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\exceptions\ApiException;
  36. use crmeb\services\CacheService;
  37. use crmeb\services\FormBuilder as Form;
  38. use crmeb\services\FormBuilder;
  39. use crmeb\services\app\WechatService;
  40. use think\Exception;
  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(400684);
  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(100000);
  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(400685);
  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 AdminException(400686);
  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 AdminException(400687);
  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 AdminException(400688);
  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 AdminException(400689);
  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 AdminException(400690);
  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 AdminException(400691);
  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 AdminException(400692);
  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 AdminException(400693);
  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 AdminException(400694);
  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 AdminException(400695);
  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. if (strpos($item['avatar'], '/statics/system_images/') !== false) {
  598. $item['avatar'] = set_file_url($item['avatar']);
  599. }
  600. }
  601. }
  602. return compact('count', 'list');
  603. }
  604. /**
  605. * 获取修改页面数据
  606. * @param int $id
  607. * @return array
  608. * @throws \FormBuilder\Exception\FormBuilderException
  609. */
  610. public function edit(int $id)
  611. {
  612. $user = $this->getUserInfo($id);
  613. if (!$user)
  614. throw new AdminException(100026);
  615. $f = array();
  616. $f[] = Form::input('uid', '用户编号', $user->getData('uid'))->disabled(true);
  617. $f[] = Form::input('real_name', '真实姓名', $user->getData('real_name'));
  618. $f[] = Form::input('phone', '手机号码', $user->getData('phone'));
  619. $f[] = Form::date('birthday', '生日', $user->getData('birthday') ? date('Y-m-d', $user->getData('birthday')) : '');
  620. $f[] = Form::input('card_id', '身份证号', $user->getData('card_id'));
  621. $f[] = Form::input('addres', '用户地址', $user->getData('addres'));
  622. $f[] = Form::textarea('mark', '用户备注', $user->getData('mark'));
  623. $f[] = Form::input('pwd', '登录密码')->type('password')->placeholder('不改密码请留空');
  624. $f[] = Form::input('true_pwd', '确认密码')->type('password')->placeholder('不改密码请留空');
  625. //查询高于当前会员的所有会员等级
  626. // $grade = app()->make(UserLevelServices::class)->getUerLevelInfoByUid($id, 'grade');
  627. $systemLevelList = app()->make(SystemUserLevelServices::class)->getWhereLevelList([], 'id,name');
  628. $setOptionLevel = function () use ($systemLevelList) {
  629. $menus = [];
  630. foreach ($systemLevelList as $menu) {
  631. $menus[] = ['value' => $menu['id'], 'label' => $menu['name']];
  632. }
  633. return $menus;
  634. };
  635. $f[] = Form::select('level', '用户等级', (int)$user->getData('level'))->setOptions(FormBuilder::setOptions($setOptionLevel))->filterable(true);
  636. $systemGroupList = app()->make(UserGroupServices::class)->getGroupList();
  637. $setOptionGroup = function () use ($systemGroupList) {
  638. $menus = [];
  639. foreach ($systemGroupList as $menu) {
  640. $menus[] = ['value' => $menu['id'], 'label' => $menu['group_name']];
  641. }
  642. return $menus;
  643. };
  644. $f[] = Form::select('group_id', '用户分组', $user->getData('group_id'))->setOptions(FormBuilder::setOptions($setOptionGroup))->filterable(true);
  645. $systemLabelList = app()->make(UserLabelServices::class)->getLabelList();
  646. $labels = app()->make(UserLabelRelationServices::class)->getUserLabels($user['uid']);
  647. $setOptionLabel = function () use ($systemLabelList) {
  648. $menus = [];
  649. foreach ($systemLabelList as $menu) {
  650. $menus[] = ['value' => $menu['id'], 'label' => $menu['label_name']];
  651. }
  652. return $menus;
  653. };
  654. $f[] = Form::select('label_id', '用户标签', $labels)->setOptions(FormBuilder::setOptions($setOptionLabel))->filterable(true)->multiple(true);
  655. $f[] = Form::radio('spread_open', '推广资格', $user->getData('spread_open'))->info('禁用用户的推广资格后,在任何分销模式下该用户都无分销权限')->options([['value' => 1, 'label' => '启用'], ['value' => 0, 'label' => '禁用']]);
  656. //分销模式 人人分销
  657. $storeBrokerageStatus = sys_config('store_brokerage_statu', 1);
  658. if ($storeBrokerageStatus == 1) {
  659. $f[] = Form::radio('is_promoter', '推广员权限', $user->getData('is_promoter'))->info('指定分销模式下,开启或关闭用户的推广权限')->options([['value' => 1, 'label' => '开启'], ['value' => 0, 'label' => '关闭']]);
  660. }
  661. $f[] = Form::radio('status', '用户状态', $user->getData('status'))->options([['value' => 1, 'label' => '开启'], ['value' => 0, 'label' => '锁定']]);
  662. return create_form('编辑', $f, Url::buildUrl('/user/user/' . $id), 'PUT');
  663. }
  664. /**
  665. * 添加用户表单
  666. * @param int $id
  667. * @return array
  668. * @throws \FormBuilder\Exception\FormBuilderException
  669. */
  670. public function saveForm()
  671. {
  672. $f = array();
  673. $f[] = Form::input('real_name', '真实姓名', '')->placeholder('请输入真实姓名');
  674. $f[] = Form::input('phone', '手机号码', '')->placeholder('请输入手机号码')->required();
  675. $f[] = Form::date('birthday', '生日', '')->placeholder('请选择生日');
  676. $f[] = Form::input('card_id', '身份证号', '')->placeholder('请输入身份证号');
  677. $f[] = Form::input('addres', '用户地址', '')->placeholder('请输入用户地址');
  678. $f[] = Form::textarea('mark', '用户备注', '')->placeholder('请输入用户备注');
  679. $f[] = Form::input('pwd', '登录密码')->type('password')->placeholder('请输入登录密码');
  680. $f[] = Form::input('true_pwd', '确认密码')->type('password')->placeholder('请再次确认密码');
  681. $systemLevelList = app()->make(SystemUserLevelServices::class)->getWhereLevelList([], 'id,name');
  682. $setOptionLevel = function () use ($systemLevelList) {
  683. $menus = [];
  684. foreach ($systemLevelList as $menu) {
  685. $menus[] = ['value' => $menu['id'], 'label' => $menu['name']];
  686. }
  687. return $menus;
  688. };
  689. $f[] = Form::select('level', '用户等级', '')->setOptions(FormBuilder::setOptions($setOptionLevel))->filterable(true);
  690. $systemGroupList = app()->make(UserGroupServices::class)->getGroupList();
  691. $setOptionGroup = function () use ($systemGroupList) {
  692. $menus = [];
  693. foreach ($systemGroupList as $menu) {
  694. $menus[] = ['value' => $menu['id'], 'label' => $menu['group_name']];
  695. }
  696. return $menus;
  697. };
  698. $f[] = Form::select('group_id', '用户分组', '')->setOptions(FormBuilder::setOptions($setOptionGroup))->filterable(true);
  699. $systemLabelList = app()->make(UserLabelServices::class)->getLabelList();
  700. $setOptionLabel = function () use ($systemLabelList) {
  701. $menus = [];
  702. foreach ($systemLabelList as $menu) {
  703. $menus[] = ['value' => $menu['id'], 'label' => $menu['label_name']];
  704. }
  705. return $menus;
  706. };
  707. $f[] = Form::select('label_id', '用户标签', '')->setOptions(FormBuilder::setOptions($setOptionLabel))->filterable(true)->multiple(true);
  708. $f[] = Form::radio('spread_open', '推广资格', 1)->info('禁用用户的推广资格后,在任何分销模式下该用户都无分销权限')->options([['value' => 1, 'label' => '启用'], ['value' => 0, 'label' => '禁用']]);
  709. //分销模式 人人分销
  710. $storeBrokerageStatus = sys_config('store_brokerage_statu', 1);
  711. if ($storeBrokerageStatus == 1) {
  712. $f[] = Form::radio('is_promoter', '推广员权限', 0)->info('指定分销模式下,开启或关闭用户的推广权限')->options([['value' => 1, 'label' => '开启'], ['value' => 0, 'label' => '关闭']]);
  713. }
  714. $f[] = Form::radio('status', '用户状态', 1)->options([['value' => 1, 'label' => '开启'], ['value' => 0, 'label' => '锁定']]);
  715. return create_form('添加用户', $f, $this->url('/user/user'), 'POST');
  716. }
  717. /**
  718. * 修改提交处理
  719. * @param $id
  720. * @return mixed
  721. */
  722. public function updateInfo(int $id, array $data)
  723. {
  724. $user = $this->getUserInfo($id);
  725. if (!$user) {
  726. throw new AdminException(100026);
  727. }
  728. $res1 = false;
  729. $res2 = false;
  730. $edit = array();
  731. if ($data['money_status'] && $data['money']) {//余额增加或者减少
  732. /** @var UserMoneyServices $userMoneyServices */
  733. $userMoneyServices = app()->make(UserMoneyServices::class);
  734. if ($data['money_status'] == 1) {//增加
  735. $edit['now_money'] = bcadd($user['now_money'], $data['money'], 2);
  736. $res1 = $userMoneyServices->income('system_add', $user['uid'], $data['money'], $edit['now_money'], $data['adminId'] ?? 0);
  737. } else if ($data['money_status'] == 2) {//减少
  738. if ($user['now_money'] > $data['money']) {
  739. $edit['now_money'] = bcsub($user['now_money'], $data['money'], 2);
  740. } else {
  741. $edit['now_money'] = 0;
  742. $data['money'] = $user['now_money'];
  743. }
  744. $res1 = $userMoneyServices->income('system_sub', $user['uid'], $data['money'], $edit['now_money'], $data['adminId'] ?? 0);
  745. }
  746. } else {
  747. $res1 = true;
  748. }
  749. if ($data['integration_status'] && $data['integration']) {//积分增加或者减少
  750. /** @var UserBillServices $userBill */
  751. $userBill = app()->make(UserBillServices::class);
  752. $integral_data = ['link_id' => $data['adminId'] ?? 0, 'number' => $data['integration']];
  753. if ($data['integration_status'] == 1) {//增加
  754. $edit['integral'] = bcadd($user['integral'], $data['integration'], 2);
  755. $integral_data['balance'] = $edit['integral'];
  756. $integral_data['title'] = '系统增加积分';
  757. $integral_data['mark'] = '系统增加了' . floatval($data['integration']) . '积分';
  758. $res2 = $userBill->incomeIntegral($user['uid'], 'system_add', $integral_data);
  759. } else if ($data['integration_status'] == 2) {//减少
  760. $edit['integral'] = bcsub($user['integral'], $data['integration'], 2);
  761. $integral_data['balance'] = $edit['integral'];
  762. $integral_data['title'] = '系统减少积分';
  763. $integral_data['mark'] = '系统扣除了' . floatval($data['integration']) . '积分';
  764. $res2 = $userBill->expendIntegral($user['uid'], 'system_sub', $integral_data);
  765. }
  766. } else {
  767. $res2 = true;
  768. }
  769. //修改基本信息
  770. if (!isset($data['is_other']) || !$data['is_other']) {
  771. app()->make(UserLabelRelationServices::class)->setUserLable([$id], $data['label_id']);
  772. if (isset($data['pwd']) && $data['pwd'] && $data['pwd'] != $user['pwd']) {
  773. $edit['pwd'] = $data['pwd'];
  774. }
  775. if (isset($data['spread_open'])) {
  776. $edit['spread_open'] = $data['spread_open'];
  777. }
  778. $edit['status'] = $data['status'];
  779. $edit['real_name'] = $data['real_name'];
  780. $edit['card_id'] = $data['card_id'];
  781. $edit['birthday'] = strtotime($data['birthday']);
  782. $edit['mark'] = $data['mark'];
  783. $edit['is_promoter'] = $data['is_promoter'];
  784. $edit['level'] = $data['level'];
  785. $edit['phone'] = $data['phone'];
  786. $edit['addres'] = $data['addres'];
  787. $edit['group_id'] = $data['group_id'];
  788. if ($user['level'] != $data['level']) {
  789. /** @var UserLevelServices $userLevelService */
  790. $userLevelService = app()->make(UserLevelServices::class);
  791. $userLevelService->setUserLevel((int)$user['uid'], (int)$data['level']);
  792. }
  793. }
  794. if ($edit) $res3 = $this->dao->update($id, $edit);
  795. else $res3 = true;
  796. if ($res1 && $res2 && $res3)
  797. return true;
  798. else throw new AdminException(100007);
  799. }
  800. /**
  801. * 编辑其他
  802. * @param $id
  803. * @return mixed
  804. * @throws \FormBuilder\Exception\FormBuilderException
  805. */
  806. public function editOther($id)
  807. {
  808. $user = $this->getUserInfo($id);
  809. if (!$user) {
  810. throw new AdminException(100026);
  811. }
  812. $f = array();
  813. $f[] = Form::radio('money_status', '修改余额', 1)->options([['value' => 1, 'label' => '增加'], ['value' => 2, 'label' => '减少']]);
  814. $f[] = Form::number('money', '余额', 0)->min(0)->max(999999.99);
  815. $f[] = Form::radio('integration_status', '修改积分', 1)->options([['value' => 1, 'label' => '增加'], ['value' => 2, 'label' => '减少']]);
  816. $f[] = Form::number('integration', '积分', 0)->min(0)->precision(0)->max(999999);
  817. return create_form('修改其他', $f, Url::buildUrl('/user/update_other/' . $id), 'PUT');
  818. }
  819. /**
  820. * 设置会员分组
  821. * @param $id
  822. * @return mixed
  823. */
  824. public function setGroup($uids)
  825. {
  826. $userGroup = app()->make(UserGroupServices::class)->getGroupList();
  827. if (count($uids) == 1) {
  828. $user = $this->getUserInfo($uids[0], ['group_id']);
  829. $setOptionUserGroup = function () use ($userGroup) {
  830. $menus = [];
  831. foreach ($userGroup as $menu) {
  832. $menus[] = ['value' => $menu['id'], 'label' => $menu['group_name']];
  833. }
  834. return $menus;
  835. };
  836. $field[] = Form::select('group_id', '用户分组', $user->getData('group_id'))->setOptions(FormBuilder::setOptions($setOptionUserGroup))->filterable(true);
  837. } else {
  838. $setOptionUserGroup = function () use ($userGroup) {
  839. $menus = [];
  840. foreach ($userGroup as $menu) {
  841. $menus[] = ['value' => $menu['id'], 'label' => $menu['group_name']];
  842. }
  843. return $menus;
  844. };
  845. $field[] = Form::select('group_id', '用户分组')->setOptions(FormBuilder::setOptions($setOptionUserGroup))->filterable(true);
  846. }
  847. $field[] = Form::hidden('uids', implode(',', $uids));
  848. return create_form('设置用户分组', $field, Url::buildUrl('/user/save_set_group'), 'PUT');
  849. }
  850. /**
  851. * 保存会员分组
  852. * @param $id
  853. * @return mixed
  854. */
  855. public function saveSetGroup($uids, int $group_id)
  856. {
  857. /** @var UserGroupServices $userGroup */
  858. $userGroup = app()->make(UserGroupServices::class);
  859. if (!$userGroup->getGroup($group_id)) {
  860. throw new AdminException(400696);
  861. }
  862. if (!$this->setUserGroup($uids, $group_id)) {
  863. throw new AdminException(400697);
  864. }
  865. return true;
  866. }
  867. /**
  868. * 设置用户标签
  869. * @param $uids
  870. * @return mixed
  871. */
  872. public function setLabel($uids)
  873. {
  874. $userLabel = app()->make(UserLabelServices::class)->getLabelList();
  875. if (count($uids) == 1) {
  876. $lids = app()->make(UserLabelRelationServices::class)->getUserLabels($uids[0]);
  877. $setOptionUserLabel = function () use ($userLabel) {
  878. $menus = [];
  879. foreach ($userLabel as $menu) {
  880. $menus[] = ['value' => $menu['id'], 'label' => $menu['label_name']];
  881. }
  882. return $menus;
  883. };
  884. $field[] = Form::select('label_id', '用户标签', $lids)->setOptions(FormBuilder::setOptions($setOptionUserLabel))->filterable(true)->multiple(true);
  885. } else {
  886. $setOptionUserLabel = function () use ($userLabel) {
  887. $menus = [];
  888. foreach ($userLabel as $menu) {
  889. $menus[] = ['value' => $menu['id'], 'label' => $menu['label_name']];
  890. }
  891. return $menus;
  892. };
  893. $field[] = Form::select('label_id', '用户标签')->setOptions(FormBuilder::setOptions($setOptionUserLabel))->filterable(true)->multiple(true);
  894. }
  895. $field[] = Form::hidden('uids', implode(',', $uids));
  896. return create_form('设置用户标签', $field, Url::buildUrl('/user/save_set_label'), 'PUT');
  897. }
  898. /**
  899. * 保存用户标签
  900. * @return mixed
  901. */
  902. public function saveSetLabel($uids, $lable_id)
  903. {
  904. foreach ($lable_id as $id) {
  905. if (!app()->make(UserLabelServices::class)->getLable((int)$id)) {
  906. throw new AdminException(400698);
  907. }
  908. }
  909. /** @var UserLabelRelationServices $services */
  910. $services = app()->make(UserLabelRelationServices::class);
  911. if (!$services->setUserLable($uids, $lable_id)) {
  912. throw new AdminException(400668);
  913. }
  914. return true;
  915. }
  916. /**
  917. * 赠送会员等级
  918. * @param int $uid
  919. * @return mixed
  920. * */
  921. public function giveLevel($id)
  922. {
  923. if (!$this->getUserInfo($id)) {
  924. throw new AdminException(400214);
  925. }
  926. //查询高于当前会员的所有会员等级
  927. $grade = app()->make(UserLevelServices::class)->getUerLevelInfoByUid($id, 'grade');
  928. $systemLevelList = app()->make(SystemUserLevelServices::class)->getWhereLevelList(['grade', '>', $grade ?? 0], 'id,name');
  929. $setOptionlevel = function () use ($systemLevelList) {
  930. $menus = [];
  931. foreach ($systemLevelList as $menu) {
  932. $menus[] = ['value' => $menu['id'], 'label' => $menu['name']];
  933. }
  934. return $menus;
  935. };
  936. $field[] = Form::select('level_id', '用户等级')->setOptions(FormBuilder::setOptions($setOptionlevel))->filterable(true);
  937. return create_form('赠送等级', $field, Url::buildUrl('/user/save_give_level/' . $id), 'PUT');
  938. }
  939. /**
  940. * 执行赠送会员等级
  941. * @param int $uid
  942. * @return mixed
  943. * */
  944. public function saveGiveLevel(int $id, int $level_id)
  945. {
  946. if (!$this->getUserInfo($id)) {
  947. throw new AdminException(400214);
  948. }
  949. /** @var SystemUserLevelServices $systemLevelServices */
  950. $systemLevelServices = app()->make(SystemUserLevelServices::class);
  951. /** @var UserLevelServices $userLevelServices */
  952. $userLevelServices = app()->make(UserLevelServices::class);
  953. //查询当前选择的会员等级
  954. $systemLevel = $systemLevelServices->getLevel($level_id);
  955. if (!$systemLevel) throw new AdminException(400699);
  956. //检查是否拥有此会员等级
  957. $level = $userLevelServices->getWhereLevel(['uid' => $id, 'level_id' => $level_id], 'valid_time,is_forever');
  958. if ($level && $level['status'] == 1 && $level['is_del'] == 0) {
  959. throw new AdminException(400700);
  960. }
  961. //保存会员信息
  962. if (!$userLevelServices->setUserLevel($id, $level_id, $systemLevel)) {
  963. throw new AdminException(400219);
  964. }
  965. return true;
  966. }
  967. /**
  968. * 赠送付费会员时长
  969. * @param int $uid
  970. * @return mixed
  971. * */
  972. public function giveLevelTime($id)
  973. {
  974. if (!$this->getUserInfo($id)) {
  975. throw new AdminException(400214);
  976. }
  977. $field[] = Form::number('days', '增加时长(天)')->precision(0)->style(['width' => '200px'])->required();
  978. return create_form('赠送付费会员时长', $field, Url::buildUrl('/user/save_give_level_time/' . $id), 'PUT');
  979. }
  980. /**
  981. * 执行赠送付费会员时长
  982. * @param int $uid
  983. * @return mixed
  984. * */
  985. public function saveGiveLevelTime(int $id, int $days)
  986. {
  987. $userInfo = $this->getUserInfo($id);
  988. if (!$userInfo) {
  989. throw new AdminException(400214);
  990. }
  991. if ($days == 0) throw new AdminException(400701);
  992. if ($days < -1) throw new AdminException(400702);
  993. if ($userInfo->is_money_level == 0) {
  994. $userInfo->is_money_level = 3;
  995. if ($days == -1) {
  996. $userInfo->is_ever_level = 1;
  997. $time = 0;
  998. } else {
  999. $userInfo->overdue_time = $time = time() + ($days * 86400);
  1000. }
  1001. } else {
  1002. if ($days == -1) {
  1003. $userInfo->is_ever_level = 1;
  1004. $time = 0;
  1005. } else {
  1006. $userInfo->overdue_time = $time = $userInfo->overdue_time + ($days * 86400);
  1007. }
  1008. }
  1009. $userInfo->save();
  1010. /** @var StoreOrderCreateServices $storeOrderCreateService */
  1011. $storeOrderCreateService = app()->make(StoreOrderCreateServices::class);
  1012. $orderInfo = [
  1013. 'uid' => $id,
  1014. 'order_id' => $storeOrderCreateService->getNewOrderId(),
  1015. 'type' => 3,
  1016. 'member_type' => 0,
  1017. 'pay_type' => 'admin',
  1018. 'paid' => 1,
  1019. 'pay_time' => time(),
  1020. 'is_free' => 1,
  1021. 'overdue_time' => $time,
  1022. 'vip_day' => $days,
  1023. 'add_time' => time()
  1024. ];
  1025. /** @var OtherOrderServices $otherOrder */
  1026. $otherOrder = app()->make(OtherOrderServices::class);
  1027. $otherOrder->save($orderInfo);
  1028. return true;
  1029. }
  1030. /**
  1031. * 清除会员等级
  1032. * @paran int $uid
  1033. * @paran boolean
  1034. * */
  1035. public function cleanUpLevel($uid)
  1036. {
  1037. if (!$this->getUserInfo($uid))
  1038. throw new AdminException(400214);
  1039. /** @var UserLevelServices $services */
  1040. $services = app()->make(UserLevelServices::class);
  1041. return $this->transaction(function () use ($uid, $services) {
  1042. $res = $services->delUserLevel($uid);
  1043. $res1 = $this->dao->update($uid, ['clean_time' => time(), 'level' => 0, 'exp' => 0], 'uid');
  1044. if (!$res && !$res1)
  1045. throw new AdminException(400186);
  1046. return true;
  1047. });
  1048. }
  1049. /**
  1050. * 用户详细信息
  1051. * @param $uid
  1052. */
  1053. public function getUserDetailed(int $uid, $userIfno = [])
  1054. {
  1055. /** @var UserAddressServices $userAddress */
  1056. $userAddress = app()->make(UserAddressServices::class);
  1057. $field = 'real_name,phone,province,city,district,detail,post_code';
  1058. $address = $userAddress->getUserDefaultAddress($uid, $field);
  1059. if (!$address) {
  1060. $address = $userAddress->getUserAddressList($uid, $field);
  1061. $address = $address[0] ?? [];
  1062. }
  1063. $userInfo = $this->getUserInfo($uid);
  1064. return [
  1065. ['name' => '默认收货地址', 'value' => $address ? '收货人:' . $address['real_name'] . '邮编:' . $address['post_code'] . ' 收货人电话:' . $address['phone'] . ' 地址:' . $address['province'] . ' ' . $address['city'] . ' ' . $address['district'] . ' ' . $address['detail'] : ''],
  1066. ['name' => '手机号码', 'value' => $userInfo['phone']],
  1067. ['name' => '姓名', 'value' => ''],
  1068. ['name' => '微信昵称', 'value' => $userInfo['nickname']],
  1069. ['name' => '头像', 'value' => $userInfo['avatar']],
  1070. ['name' => '邮箱', 'value' => ''],
  1071. ['name' => '生日', 'value' => ''],
  1072. ['name' => '积分', 'value' => $userInfo['integral']],
  1073. ['name' => '上级推广人', 'value' => $userInfo['spread_uid'] ? $this->getUserInfo($userInfo['spread_uid'], ['nickname'])['nickname'] ?? '' : ''],
  1074. ['name' => '账户余额', 'value' => $userInfo['now_money']],
  1075. ['name' => '佣金总收入', 'value' => app()->make(UserBillServices::class)->getBrokerageSum($uid)],
  1076. ['name' => '提现总金额', 'value' => app()->make(UserExtractServices::class)->getUserExtract($uid)],
  1077. ];
  1078. }
  1079. /**
  1080. * 获取用户详情里面的用户消费能力和用户余额积分等
  1081. * @param $uid
  1082. * @return array[]
  1083. */
  1084. public function getHeaderList(int $uid, $userInfo = [])
  1085. {
  1086. if (!$userInfo) {
  1087. $userInfo = $this->getUserInfo($uid);
  1088. }
  1089. /** @var StoreOrderServices $orderServices */
  1090. $orderServices = app()->make(StoreOrderServices::class);
  1091. $where = ['uid' => $uid, 'paid' => 1, 'refund_status' => 0, 'pid' => 0];
  1092. return [
  1093. [
  1094. 'title' => '余额',
  1095. 'value' => $userInfo['now_money'] ?? 0,
  1096. 'key' => '元',
  1097. ],
  1098. [
  1099. 'title' => '总计订单',
  1100. 'value' => $orderServices->count($where),
  1101. 'key' => '笔',
  1102. ],
  1103. [
  1104. 'title' => '总消费金额',
  1105. 'value' => $orderServices->together($where, 'pay_price'),
  1106. 'key' => '元',
  1107. ],
  1108. [
  1109. 'title' => '积分',
  1110. 'value' => $userInfo['integral'] ?? 0,
  1111. 'key' => '',
  1112. ],
  1113. [
  1114. 'title' => '本月订单',
  1115. 'value' => $orderServices->count($where + ['time' => 'month']),
  1116. 'key' => '笔',
  1117. ],
  1118. [
  1119. 'title' => '本月消费金额',
  1120. 'value' => $orderServices->together($where + ['time' => 'month'], 'pay_price'),
  1121. 'key' => '元',
  1122. ]
  1123. ];
  1124. }
  1125. /**
  1126. * 获取用户记录里的积分总数和签到总数和余额变动总数
  1127. * @param $uid
  1128. * @return array
  1129. */
  1130. public function getUserBillCountData($uid)
  1131. {
  1132. /** @var UserBillServices $userBill */
  1133. $userBill = app()->make(UserBillServices::class);
  1134. $integral_count = $userBill->getIntegralCount($uid);
  1135. $sign_count = $userBill->getSignCount($uid);
  1136. $balanceChang_count = $userBill->getBrokerageCount($uid);
  1137. return [$integral_count, $sign_count, $balanceChang_count];
  1138. }
  1139. public function read(int $uid)
  1140. {
  1141. $userInfo = $this->getUserInfo($uid);
  1142. if (!$userInfo) {
  1143. throw new AdminException(100026);
  1144. }
  1145. $info = [
  1146. 'uid' => $uid,
  1147. 'userinfo' => $this->getUserDetailed($uid, $userInfo),
  1148. 'headerList' => $this->getHeaderList($uid, $userInfo),
  1149. 'count' => $this->getUserBillCountData($uid),
  1150. 'ps_info' => $userInfo
  1151. ];
  1152. return $info;
  1153. }
  1154. /**
  1155. * 获取好友
  1156. * @param int $id
  1157. * @param string $field
  1158. * @return array
  1159. * @throws \think\db\exception\DataNotFoundException
  1160. * @throws \think\db\exception\DbException
  1161. * @throws \think\db\exception\ModelNotFoundException
  1162. */
  1163. public function getFriendList(int $id, string $field = 'uid,nickname,level,add_time,spread_time')
  1164. {
  1165. [$page, $limit] = $this->getPageValue();
  1166. $list = $this->dao->getList(['spread_uid' => $id], $field, $page, $limit);
  1167. /** @var SystemUserLevelServices $systemLevelServices */
  1168. $systemLevelServices = app()->make(SystemUserLevelServices::class);
  1169. $systemLevelList = $systemLevelServices->getWhereLevelList([], 'id,name');
  1170. if ($systemLevelServices) $systemLevelServices = array_combine(array_column($systemLevelList, 'id'), $systemLevelList);
  1171. foreach ($list as &$item) {
  1172. $item['type'] = $systemLevelServices[$item['level']]['name'] ?? '暂无';
  1173. $item['add_time'] = $item['spread_time'] && is_numeric($item['spread_time']) ? date('Y-m-d H:i:s', $item['spread_time']) : '';
  1174. }
  1175. $count = $this->dao->count(['spread_uid' => $id]);
  1176. return compact('list', 'count');
  1177. }
  1178. /**
  1179. * 获取单个用户信息
  1180. * @param $id 用户id
  1181. * @return mixed
  1182. */
  1183. public function oneUserInfo(int $id, string $type)
  1184. {
  1185. switch ($type) {
  1186. case 'spread':
  1187. // /** @var UserFriendsServices $services */
  1188. // $services = app()->make(UserFriendsServices::class);
  1189. // return $services->getFriendList(['uid' => $id], ['level', 'nickname']);
  1190. return $this->getFriendList($id);
  1191. case 'order':
  1192. /** @var StoreOrderServices $services */
  1193. $services = app()->make(StoreOrderServices::class);
  1194. return $services->getUserOrderList($id);
  1195. case 'integral':
  1196. /** @var UserBillServices $services */
  1197. $services = app()->make(UserBillServices::class);
  1198. return $services->getIntegralList($id, [], 'title,number,balance,mark,add_time,frozen_time');
  1199. case 'sign':
  1200. /** @var UserBillServices $services */
  1201. $services = app()->make(UserBillServices::class);
  1202. return $services->getSignList($id, [], 'title,number,mark,add_time');
  1203. case 'coupon':
  1204. /** @var StoreCouponUserServices $services */
  1205. $services = app()->make(StoreCouponUserServices::class);
  1206. return $services->getUserCouponList($id);
  1207. case 'balance_change':
  1208. /** @var UserMoneyServices $services */
  1209. $services = app()->make(UserMoneyServices::class);
  1210. return $services->balanceList(['uid' => $id]);
  1211. default:
  1212. throw new AdminException(100100);
  1213. }
  1214. }
  1215. /**获取特定时间用户访问量
  1216. * @param $time
  1217. * @param $week
  1218. * @return int
  1219. */
  1220. public function todayLastVisits($time, $week)
  1221. {
  1222. return $this->dao->todayLastVisit($time, $week);
  1223. }
  1224. /**获取特定时间新增用户
  1225. * @param $time
  1226. * @param $week
  1227. * @return int
  1228. */
  1229. public function todayAddVisits($time, $week)
  1230. {
  1231. return $this->dao->todayAddVisit($time, $week);
  1232. }
  1233. /**
  1234. * 用户图表
  1235. */
  1236. public function userChart()
  1237. {
  1238. $starday = date('Y-m-d', strtotime('-30 day'));
  1239. $yesterday = date('Y-m-d', strtotime('+1 day'));
  1240. $user_list = $this->dao->userList($starday, $yesterday);
  1241. $chartdata = [];
  1242. $data = [];
  1243. $chartdata['legend'] = ['用户数'];//分类
  1244. $chartdata['yAxis']['maxnum'] = 0;//最大值数量
  1245. $chartdata['xAxis'] = [date('m-d')];//X轴值
  1246. $chartdata['series'] = [0];//分类1值
  1247. if (!empty($user_list)) {
  1248. foreach ($user_list as $k => $v) {
  1249. $data['day'][] = $v['day'];
  1250. $data['count'][] = $v['count'];
  1251. if ($chartdata['yAxis']['maxnum'] < $v['count'])
  1252. $chartdata['yAxis']['maxnum'] = $v['count'];
  1253. }
  1254. $chartdata['xAxis'] = $data['day'];//X轴值
  1255. $chartdata['series'] = $data['count'];//分类1值
  1256. }
  1257. $chartdata['bing_xdata'] = ['未消费用户', '消费一次用户', '留存客户', '回流客户'];
  1258. $color = ['#5cadff', '#b37feb', '#19be6b', '#ff9900'];
  1259. $pay[0] = $this->dao->count(['pay_count' => 0]);
  1260. $pay[1] = $this->dao->count(['pay_count' => 1]);
  1261. $pay[2] = $this->dao->userCount(1);
  1262. $pay[3] = $this->dao->userCount(2);
  1263. foreach ($pay as $key => $item) {
  1264. $bing_data[] = ['name' => $chartdata['bing_xdata'][$key], 'value' => $pay[$key], 'itemStyle' => ['color' => $color[$key]]];
  1265. }
  1266. $chartdata['bing_data'] = $bing_data;
  1267. return $chartdata;
  1268. }
  1269. /***********************************************/
  1270. /************ 前端api services *****************/
  1271. /***********************************************/
  1272. /**
  1273. * 用户信息
  1274. * @param $info
  1275. * @return mixed
  1276. */
  1277. public function userInfo($info)
  1278. {
  1279. /** @var UserBillServices $userBill */
  1280. $userBill = app()->make(UserBillServices::class);
  1281. $uid = (int)$info['uid'];
  1282. $broken_time = intval(sys_config('extract_time'));
  1283. $search_time = time() - 86400 * $broken_time;
  1284. //改造时间
  1285. $search_time = '1970/01/01' . ' - ' . date('Y/m/d H:i:s', $search_time);
  1286. //可提现佣金
  1287. //返佣 +
  1288. $brokerage_commission = (string)$userBill->getUsersBokerageSum(['uid' => $uid, 'pm' => 1], $search_time);
  1289. //退款退的佣金 -
  1290. $refund_commission = (string)$userBill->getUsersBokerageSum(['uid' => $uid, 'pm' => 0], $search_time);
  1291. $info['broken_commission'] = bcsub($brokerage_commission, $refund_commission, 2);
  1292. if ($info['broken_commission'] < 0)
  1293. $info['broken_commission'] = 0;
  1294. $info['commissionCount'] = bcsub($info['brokerage_price'], $info['broken_commission'], 2);
  1295. if ($info['commissionCount'] < 0)
  1296. $info['commissionCount'] = 0;
  1297. return $info;
  1298. }
  1299. /**
  1300. * 个人中心
  1301. * @param array $user
  1302. */
  1303. public function personalHome(array $user, $tokenData)
  1304. {
  1305. $userInfo = $user;
  1306. $uid = (int)$user['uid'];
  1307. /** @var StoreCouponUserServices $storeCoupon */
  1308. $storeCoupon = app()->make(StoreCouponUserServices::class);
  1309. /** @var UserBillServices $userBill */
  1310. $userBill = app()->make(UserBillServices::class);
  1311. /** @var UserExtractServices $userExtract */
  1312. $userExtract = app()->make(UserExtractServices::class);
  1313. /** @var StoreOrderServices $storeOrder */
  1314. $storeOrder = app()->make(StoreOrderServices::class);
  1315. /** @var UserLevelServices $userLevel */
  1316. $userLevel = app()->make(UserLevelServices::class);
  1317. /** @var StoreServiceServices $storeService */
  1318. $storeService = app()->make(StoreServiceServices::class);
  1319. /** @var WechatUserServices $wechatUser */
  1320. $wechatUser = app()->make(WechatUserServices::class);
  1321. /** @var UserInvoiceServices $userInvoice */
  1322. $userInvoice = app()->make(UserInvoiceServices::class);
  1323. /** @var MemberCardServices $memberCardService */
  1324. $memberCardService = app()->make(MemberCardServices::class);
  1325. /** @var StoreProductRelationServices $collect */
  1326. $collect = app()->make(StoreProductRelationServices::class);
  1327. /** @var MessageSystemServices $messageSystemServices */
  1328. $messageSystemServices = app()->make(MessageSystemServices::class);
  1329. /** @var DiyServices $diyServices */
  1330. $diyServices = app()->make(DiyServices::class);
  1331. /** @var AgentLevelServices $agentLevelServices */
  1332. $agentLevelServices = app()->make(AgentLevelServices::class);
  1333. //看付费会员是否开启
  1334. $isOpenMember = $memberCardService->isOpenMemberCard();
  1335. $user['is_open_member'] = $isOpenMember;
  1336. $user['agent_level_name'] = '';
  1337. if ($user['agent_level']) {
  1338. $levelInfo = $agentLevelServices->getLevelInfo((int)$user['agent_level'], 'id,name,status,grade');
  1339. if (!$levelInfo['status']) {
  1340. $levelInfo = $agentLevelServices->get([
  1341. ['grade', '<', $levelInfo['grade']],
  1342. ['is_del', '=', 0],
  1343. ['status', '=', 1]
  1344. ], ['id', 'name', 'status', 'grade']);
  1345. }
  1346. $user['agent_level_name'] = $levelInfo && $levelInfo['name'] && $levelInfo['status'] ? $levelInfo['name'] : '';
  1347. }
  1348. //会员领取优惠券
  1349. // $couponService->sendMemberCoupon($uid);
  1350. //看是否会员过期
  1351. $this->offMemberLevel($uid, $userInfo);
  1352. $wechatUserInfo = $wechatUser->getOne(['uid' => $uid, 'user_type' => $tokenData['type']]);
  1353. $user['is_complete'] = $wechatUserInfo['is_complete'] ?? 0;
  1354. $user['couponCount'] = $storeCoupon->getUserValidCouponCount((int)$uid);
  1355. $user['like'] = app()->make(StoreProductRelationServices::class)->getUserCollectCount($user['uid']);
  1356. $user['orderStatusNum'] = $storeOrder->getOrderData($uid, true, true);
  1357. $user['notice'] = 0;
  1358. /** @var UserMoneyServices $userMoney */
  1359. $userMoney = app()->make(UserMoneyServices::class);
  1360. $user['recharge'] = $userMoney->sum([
  1361. ['uid', '=', $uid], ['pm', '=', 1], ['type', 'in', ['recharge', 'system_add', 'extract']]
  1362. ], 'number');
  1363. $user['orderStatusSum'] = bcsub((string)$user['recharge'], (string)$user['now_money'], 2);
  1364. $user['extractTotalPrice'] = $userExtract->getExtractSum(['uid' => $uid, 'status' => 1]);//累计提现
  1365. $user['extractPrice'] = $user['brokerage_price'];//可提现
  1366. $user['statu'] = (int)sys_config('store_brokerage_statu');
  1367. if (!$user['is_promoter'] && $user['statu'] == 2) {
  1368. $price = $storeOrder->sum(['paid' => 1, 'refund_status' => 0, 'uid' => $user['uid']], 'pay_price');
  1369. $status = is_brokerage_statu($price);
  1370. if ($status) {
  1371. $this->dao->update($uid, ['is_promoter' => 1], 'uid');
  1372. $user['is_promoter'] = 1;
  1373. } else {
  1374. $storeBrokeragePrice = sys_config('store_brokerage_price', 0);
  1375. $user['promoter_price'] = bcsub((string)$storeBrokeragePrice, (string)$price, 2);
  1376. }
  1377. }
  1378. /** @var UserBrokerageServices $frozenPrices */
  1379. $frozenPrices = app()->make(UserBrokerageServices::class);
  1380. $user['broken_commission'] = $frozenPrices->getUserFrozenPrice($uid);
  1381. if ($user['broken_commission'] < 0)
  1382. $user['broken_commission'] = 0;
  1383. $user['commissionCount'] = bcsub((string)$user['brokerage_price'], (string)$user['broken_commission'], 2);
  1384. if ($user['commissionCount'] < 0)
  1385. $user['commissionCount'] = 0;
  1386. if (!sys_config('member_func_status'))
  1387. $user['vip'] = false;
  1388. else {
  1389. $userLevel = $userLevel->getUerLevelInfoByUid($user['uid']);
  1390. $user['vip'] = (bool)$userLevel;
  1391. if ($user['vip']) {
  1392. $user['vip_id'] = $userLevel['id'] ?? 0;
  1393. $user['vip_icon'] = $userLevel['icon'] ?? '';
  1394. $user['vip_name'] = $userLevel['name'] ?? '';
  1395. }
  1396. }
  1397. $user['yesterDay'] = $userBill->getUsersBokerageSum(['uid' => $uid, 'pm' => 1], 'yesterday');
  1398. $user['recharge_switch'] = (int)sys_config('recharge_switch');//充值开关
  1399. $user['adminid'] = $storeService->checkoutIsService(['uid' => $uid, 'status' => 1, 'customer' => 1]);
  1400. if ($user['phone'] && $user['user_type'] != 'h5') {
  1401. $user['switchUserInfo'][] = $userInfo;
  1402. $h5UserInfo = $this->dao->getOne(['account' => $user['phone'], 'user_type' => 'h5']);
  1403. if ($h5UserInfo) {
  1404. $user['switchUserInfo'][] = $h5UserInfo;
  1405. }
  1406. } else if ($user['phone'] && $user['user_type'] == 'h5') {
  1407. $wechatUserInfo = $this->getOne([['phone', '=', $user['phone']], ['user_type', '<>', 'h5']]);
  1408. if ($wechatUserInfo) {
  1409. $user['switchUserInfo'][] = $wechatUserInfo;
  1410. }
  1411. $user['switchUserInfo'][] = $userInfo;
  1412. } else if (!$user['phone']) {
  1413. $user['switchUserInfo'][] = $userInfo;
  1414. }
  1415. $user['broken_day'] = (int)sys_config('extract_time');//佣金冻结时间
  1416. $user['balance_func_status'] = (int)sys_config('balance_func_status', 0);
  1417. $invoice_func = $userInvoice->invoiceFuncStatus();
  1418. $user['invioce_func'] = $invoice_func['invoice_func'];
  1419. $user['special_invoice'] = $invoice_func['special_invoice'];
  1420. $user['collectCount'] = $collect->count(['uid' => $uid]);
  1421. $user['spread_status'] = $this->checkUserPromoter($user['uid']);
  1422. $user['pay_vip_status'] = $user['is_ever_level'] || ($user['is_money_level'] && $user['overdue_time'] > time());
  1423. $user['member_style'] = (int)$diyServices->getColorChange('member');
  1424. if ($user['is_ever_level']) {
  1425. $user['vip_status'] = 1;//永久会员
  1426. } else {
  1427. if (!$user['is_money_level'] && $user['overdue_time'] && $user['overdue_time'] < time()) {
  1428. $user['vip_status'] = -1;//开通过已过期
  1429. } else if (!$user['overdue_time'] && !$user['is_money_level']) {
  1430. $user['vip_status'] = 2;//没有开通过
  1431. } else if ($user['is_money_level'] && $user['overdue_time'] && $user['overdue_time'] > time()) {
  1432. $user['vip_status'] = 3;//开通了,没有到期
  1433. }
  1434. }
  1435. $user['svip_open'] = (bool)sys_config('member_card_status');
  1436. /** @var StoreServiceRecordServices $servicesRecord */
  1437. $servicesRecord = app()->make(StoreServiceRecordServices::class);
  1438. $service_num = $servicesRecord->sum(['user_id' => $uid], 'mssage_num');
  1439. $message = $messageSystemServices->count(['uid' => $uid, 'look' => 0, 'is_del' => 0]);
  1440. $user['service_num'] = $service_num + $message;
  1441. /** @var AgentLevelServices $userSpread */
  1442. $agentLevel = app()->make(AgentLevelServices::class);
  1443. $user['spread_level_count'] = $agentLevel->count(['status' => 1, 'is_del' => 0]);
  1444. $user['extract_type'] = sys_config('extract_type');
  1445. $user['integral'] = intval($user['integral']);
  1446. $user['is_agent_level'] = $agentLevelServices->count(['status' => 1, 'is_del' => 0]) > 0 ? 1 : 0;
  1447. $user['division_open'] = (int)sys_config('division_status', 1);
  1448. $user['avatar'] = strpos($user['avatar'], '/statics/system_images/') !== false ? set_file_url($user['avatar']) : $user['avatar'];
  1449. return $user;
  1450. }
  1451. /**
  1452. * 用户资金统计
  1453. * @param int $uid
  1454. */
  1455. public function balance(int $uid)
  1456. {
  1457. $userInfo = $this->getUserInfo($uid);
  1458. if (!$userInfo) {
  1459. throw new AdminException(400214);
  1460. }
  1461. /** @var UserBillServices $userBill */
  1462. $userBill = app()->make(UserBillServices::class);
  1463. /** @var StoreOrderServices $storeOrder */
  1464. $storeOrder = app()->make(StoreOrderServices::class);
  1465. $user['now_money'] = $userInfo['now_money'];//当前总资金
  1466. $user['recharge'] = $userBill->getRechargeSum($uid);//累计充值
  1467. $user['orderStatusSum'] = $storeOrder->sum(['uid' => $uid, 'paid' => 1, 'is_del' => 0], 'pay_price');//累计消费
  1468. return $user;
  1469. }
  1470. /**
  1471. * 用户修改信息
  1472. * @param Request $request
  1473. * @return mixed
  1474. */
  1475. public function eidtNickname(int $uid, array $data)
  1476. {
  1477. if (!$this->getUserInfo($uid)) {
  1478. throw new ApiException(400214);
  1479. }
  1480. if (!$this->dao->update($uid, $data, 'uid')) {
  1481. throw new ApiException(100007);
  1482. }
  1483. return true;
  1484. }
  1485. /**
  1486. * 获取推广人排行
  1487. * @param $data 查询条件
  1488. * @return array
  1489. * @throws \think\db\exception\DataNotFoundException
  1490. * @throws \think\db\exception\ModelNotFoundException
  1491. * @throws \think\exception\DbException
  1492. */
  1493. public function getRankList(array $data)
  1494. {
  1495. $startTime = strtotime('this week Monday');
  1496. $endTime = time();
  1497. switch ($data['type']) {
  1498. case 'week':
  1499. $startTime = strtotime('this week Monday');
  1500. break;
  1501. case 'month':
  1502. $startTime = strtotime('last month');
  1503. break;
  1504. }
  1505. [$page, $limit] = $this->getPageValue();
  1506. $field = 't0.uid,t0.spread_uid,count(t1.spread_uid) AS count,t0.add_time,t0.nickname,t0.avatar';
  1507. return $this->dao->getAgentRankList([$startTime, $endTime], $field, $page, $limit);
  1508. }
  1509. /**
  1510. * 静默绑定推广人
  1511. * @param Request $request
  1512. * @return mixed
  1513. */
  1514. public function spread(int $uid, int $spreadUid, $code)
  1515. {
  1516. $userInfo = $this->getUserInfo($uid);
  1517. if (!$userInfo) {
  1518. throw new ApiException(100026);
  1519. }
  1520. if ($code && !$spreadUid) {
  1521. /** @var QrcodeServices $qrCode */
  1522. $qrCode = app()->make(QrcodeServices::class);
  1523. if ($info = $qrCode->getOne(['id' => $code, 'status' => 1])) {
  1524. $spreadUid = $info['third_id'];
  1525. }
  1526. }
  1527. $userSpreadUid = $this->dao->value(['uid' => $spreadUid], 'spread_uid');
  1528. //记录好友关系
  1529. if ($spreadUid && $uid && $spreadUid != $uid) {
  1530. /** @var UserFriendsServices $serviceFriend */
  1531. $serviceFriend = app()->make(UserFriendsServices::class);
  1532. $serviceFriend->saveFriend([
  1533. 'uid' => $uid,
  1534. 'friends_uid' => $spreadUid,
  1535. ]);
  1536. }
  1537. //记录上下级关系
  1538. if (!$userInfo['spread_uid'] && $spreadUid != $uid && $userSpreadUid != $userInfo['uid']) {
  1539. if ((sys_config('brokerage_bindind') == 2 && $userInfo['add_time'] == $userInfo['last_time']) || sys_config('brokerage_bindind') == 1) {
  1540. $spreadInfo = $this->dao->get($spreadUid);
  1541. $data = [];
  1542. $data['spread_uid'] = $spreadUid;
  1543. $data['spread_time'] = time();
  1544. $data['division_id'] = $spreadInfo['division_id'];
  1545. $data['agent_id'] = $spreadInfo['agent_id'];
  1546. $data['staff_id'] = $spreadInfo['staff_id'];
  1547. if (!$this->dao->update($uid, $data, 'uid')) {
  1548. throw new ApiException(410288);
  1549. }
  1550. /** @var UserBillServices $userBill */
  1551. $userBill = app()->make(UserBillServices::class);
  1552. //邀请新用户增加经验
  1553. $userBill->inviteUserIncExp((int)$spreadUid);
  1554. }
  1555. }
  1556. return true;
  1557. }
  1558. /**
  1559. * 添加访问记录
  1560. * @param Request $request
  1561. * @return mixed
  1562. */
  1563. public function setVisit(array $data)
  1564. {
  1565. $userInfo = $this->getUserInfo($data['uid']);
  1566. if (!$userInfo) {
  1567. throw new ApiException(100026);
  1568. }
  1569. $data['channel_type'] = $userInfo['user_type'];
  1570. $data['add_time'] = time();
  1571. /** @var WechatUserServices $wechatUserServices */
  1572. $wechatUserServices = app()->make(WechatUserServices::class);
  1573. $wechatUser = $wechatUserServices->get(['uid' => $userInfo['uid'], 'user_type' => $userInfo['user_type']]);
  1574. if (!$wechatUser) {
  1575. $wechatUser = $wechatUserServices->get(['uid' => $userInfo['uid']]);
  1576. }
  1577. if ($wechatUser) {
  1578. $data['province'] = $wechatUser['province'];
  1579. }
  1580. /** @var UserVisitServices $userVisit */
  1581. $userVisit = app()->make(UserVisitServices::class);
  1582. if ($userVisit->save($data)) {
  1583. return true;
  1584. } else {
  1585. throw new ApiException(100015);
  1586. }
  1587. }
  1588. /**
  1589. * 获取活动状态
  1590. * @return mixed
  1591. */
  1592. public function activity()
  1593. {
  1594. /** @var StoreBargainServices $storeBragain */
  1595. $storeBragain = app()->make(StoreBargainServices::class);
  1596. /** @var StoreCombinationServices $storeCombinaion */
  1597. $storeCombinaion = app()->make(StoreCombinationServices::class);
  1598. /** @var StoreSeckillServices $storeSeckill */
  1599. $storeSeckill = app()->make(StoreSeckillServices::class);
  1600. $data['is_bargin'] = (bool)$storeBragain->validBargain();
  1601. $data['is_pink'] = (bool)$storeCombinaion->validCombination();
  1602. $data['is_seckill'] = (bool)$storeSeckill->getSeckillCount();
  1603. return $data;
  1604. }
  1605. /**
  1606. * 获取用户下级推广人
  1607. * @param int $uid 当前用户
  1608. * @param int $grade 等级 0 一级 1 二级
  1609. * @param string $orderBy 排序
  1610. * @param string $keyword
  1611. * @return array|bool
  1612. */
  1613. public function getUserSpreadGrade(int $uid = 0, $grade = 0, $orderBy = '', $keyword = '')
  1614. {
  1615. $user = $this->getUserInfo($uid);
  1616. if (!$user) {
  1617. throw new AdminException(400214);
  1618. }
  1619. $spread_one_ids = $this->getUserSpredadUids($uid, 1);
  1620. $spread_two_ids = $this->getUserSpredadUids($uid, 2);
  1621. $data = [
  1622. 'total' => count($spread_one_ids),
  1623. 'totalLevel' => count($spread_two_ids),
  1624. 'list' => []
  1625. ];
  1626. if (sys_config('brokerage_level', 2) == 1) {
  1627. $data['count'] = $data['total'];
  1628. } else {
  1629. $data['count'] = $data['total'] + $data['totalLevel'];
  1630. }
  1631. /** @var UserStoreOrderServices $userStoreOrder */
  1632. $userStoreOrder = app()->make(UserStoreOrderServices::class);
  1633. $list = [];
  1634. if ($grade == 0) {
  1635. if ($spread_one_ids) $list = $userStoreOrder->getUserSpreadCountList($spread_one_ids, $orderBy, $keyword);
  1636. } else {
  1637. if ($spread_two_ids) $list = $userStoreOrder->getUserSpreadCountList($spread_two_ids, $orderBy, $keyword);
  1638. }
  1639. foreach ($list as &$item) {
  1640. if (isset($item['spread_time']) && $item['spread_time']) {
  1641. $item['time'] = date('Y/m/d', $item['spread_time']);
  1642. }
  1643. }
  1644. $data['list'] = $list;
  1645. $data['brokerage_level'] = (int)sys_config('brokerage_level', 2);
  1646. return $data;
  1647. }
  1648. /**
  1649. * 获取推广人uids
  1650. * @param int $uid
  1651. * @param bool $one
  1652. * @return array
  1653. */
  1654. public function getUserSpredadUids(int $uid, int $type = 0)
  1655. {
  1656. $uids = $this->dao->getColumn(['spread_uid' => $uid, 'is_del' => 0], 'uid');
  1657. if ($type === 1) {
  1658. return $uids;
  1659. }
  1660. if ($uids) {
  1661. $uidsTwo = $this->dao->getColumn([['spread_uid', 'in', $uids], ['is_del', '=', 0]], 'uid');
  1662. if ($type === 2) {
  1663. return $uidsTwo;
  1664. }
  1665. if ($uidsTwo) {
  1666. $uids = array_merge($uids, $uidsTwo);
  1667. }
  1668. }
  1669. return $uids;
  1670. }
  1671. /**
  1672. * 检测用户是否是推广员
  1673. * @param int $uid
  1674. * @param $user
  1675. * @return bool
  1676. */
  1677. public function checkUserPromoter(int $uid, $user = [])
  1678. {
  1679. if (!$user) {
  1680. $user = $this->getUserInfo($uid);
  1681. }
  1682. if (!$user) {
  1683. return false;
  1684. }
  1685. //分销是否开启
  1686. if (!sys_config('brokerage_func_status')) {
  1687. return false;
  1688. }
  1689. //用户分校推广资格是否开启4.0.32
  1690. if (isset($user['spread_open']) && !$user['spread_open']) {
  1691. return false;
  1692. }
  1693. /** @var StoreOrderServices $storeOrder */
  1694. $storeOrder = app()->make(StoreOrderServices::class);
  1695. $sumPrice = $storeOrder->sum(['uid' => $uid, 'paid' => 1, 'is_del' => 0], 'pay_price');//累计消费
  1696. $store_brokerage_statu = sys_config('store_brokerage_statu');
  1697. $store_brokerage_price = sys_config('store_brokerage_price');
  1698. if ($user['is_promoter'] || $store_brokerage_statu == 2 || ($store_brokerage_statu == 3 && $sumPrice > $store_brokerage_price)) {
  1699. return true;
  1700. }
  1701. return false;
  1702. }
  1703. /**
  1704. * 同步微信粉丝用户(后台接口)
  1705. * @return bool
  1706. */
  1707. public function syncWechatUsers()
  1708. {
  1709. $appid = sys_config('wechat_appid');
  1710. $appSecret = sys_config('wechat_appsecret');
  1711. if (!$appid || !$appSecret) {
  1712. throw new AdminException(400236);
  1713. }
  1714. $key = md5('sync_wechat_users');
  1715. //一天点击一次
  1716. if (CacheService::get($key)) {
  1717. return true;
  1718. }
  1719. $next_openid = null;
  1720. do {
  1721. $result = WechatService::getUsersList($next_openid);
  1722. $userOpenids = $result['data'];
  1723. //拆分大数组
  1724. $opemidArr = array_chunk($userOpenids, 100);
  1725. foreach ($opemidArr as $openids) {
  1726. //加入同步|更新用户队列
  1727. UserJob::dispatch([$openids]);
  1728. }
  1729. $next_openid = $result['next_openid'];
  1730. } while ($next_openid != null);
  1731. CacheService::set($key, 1, 3600 * 24);
  1732. return true;
  1733. }
  1734. /**
  1735. * 导入微信粉丝用户
  1736. * @param array $openids
  1737. * @return bool
  1738. */
  1739. public function importUser(array $noBeOpenids)
  1740. {
  1741. if (!$noBeOpenids) {
  1742. return true;
  1743. }
  1744. $dataAll = $data = [];
  1745. $time = time();
  1746. foreach ($noBeOpenids as $openid) {
  1747. try {
  1748. $info = WechatService::getUserInfo($openid);
  1749. $info = is_object($info) ? $info->toArray() : $info;
  1750. } catch (\Throwable $e) {
  1751. $info = [];
  1752. }
  1753. if (!$info) continue;
  1754. $data['nickname'] = $info['nickname'] ?? '';
  1755. $data['headimgurl'] = $info['headimgurl'] ?? '';
  1756. $userInfoData = $this->setUserInfo($data);
  1757. if (!$userInfoData) {
  1758. throw new AdminException(400703);
  1759. }
  1760. $data['uid'] = $userInfoData['uid'];
  1761. $data['subscribe'] = $info['subscribe'] ?? 1;
  1762. $data['unionid'] = $info['unionid'] ?? '';
  1763. $data['openid'] = $info['openid'] ?? '';
  1764. $data['sex'] = $info['sex'] ?? 0;
  1765. $data['language'] = $info['language'] ?? '';
  1766. $data['city'] = $info['city'] ?? '';
  1767. $data['province'] = $info['province'] ?? '';
  1768. $data['country'] = $info['country'] ?? '';
  1769. $data['subscribe_time'] = $info['subscribe_time'] ?? '';
  1770. $data['groupid'] = $info['groupid'] ?? 0;
  1771. $data['remark'] = $info['remark'] ?? '';
  1772. $data['tagid_list'] = isset($info['tagid_list']) && $info['tagid_list'] ? implode(',', $info['tagid_list']) : '';
  1773. $data['add_time'] = $time;
  1774. $data['is_complete'] = 1;
  1775. $dataAll[] = $data;
  1776. }
  1777. if ($dataAll) {
  1778. /** @var WechatUserServices $wechatUser */
  1779. $wechatUser = app()->make(WechatUserServices::class);
  1780. if (!$wechatUser->saveAll($dataAll)) {
  1781. throw new AdminException(400703);
  1782. }
  1783. }
  1784. return true;
  1785. }
  1786. /** 修改会员的时间及是否会员状态
  1787. * @param int $vip_day 会员天数
  1788. * @param array $user_id 用户id
  1789. * @param int $is_money_level 会员来源途径
  1790. * @param bool $member_type 会员卡类型
  1791. * @return mixed
  1792. * @throws \think\db\exception\DataNotFoundException
  1793. * @throws \think\db\exception\DbException
  1794. * @throws \think\db\exception\ModelNotFoundException
  1795. */
  1796. public function setMemberOverdueTime($vip_day, int $user_id, int $is_money_level, $member_type = false)
  1797. {
  1798. if ($vip_day == 0) throw new ApiException(410289);
  1799. $user_info = $this->getUserInfo($user_id);
  1800. if (!$user_info) throw new ApiException(410032);
  1801. if (!$member_type) $member_type = "month";
  1802. if ($member_type == 'ever') {
  1803. $overdue_time = 0;
  1804. $is_ever_level = 1;
  1805. } else {
  1806. if ($user_info['is_money_level'] == 0) {
  1807. $overdue_time = bcadd(bcmul($vip_day, 86400, 0), time(), 0);
  1808. } else {
  1809. $overdue_time = bcadd(bcmul($vip_day, 86400, 0), $user_info['overdue_time'], 0);
  1810. }
  1811. $is_ever_level = 0;
  1812. }
  1813. $setData['overdue_time'] = $overdue_time;
  1814. $setData['is_ever_level'] = $is_ever_level;
  1815. $setData['is_money_level'] = $is_money_level ?: 0;
  1816. // if ($user_info['level'] == 0) $setData['level'] = 1;
  1817. return $this->dao->update(['uid' => $user_id], $setData);
  1818. }
  1819. /**
  1820. * 会员过期改变状态,变为普通会员
  1821. * @param $uid
  1822. * @param $userInfo
  1823. * @return bool
  1824. * @throws \think\db\exception\DataNotFoundException
  1825. * @throws \think\db\exception\DbException
  1826. * @throws \think\db\exception\ModelNotFoundException
  1827. */
  1828. public function offMemberLevel($uid, $userInfo = [])
  1829. {
  1830. if (!$uid) return false;
  1831. if (!$userInfo) {
  1832. $userInfo = $this->dao->get($uid);
  1833. }
  1834. if (!$userInfo) return false;
  1835. if ($userInfo['is_ever_level'] == 0 && $userInfo['is_money_level'] > 0 && $userInfo['overdue_time'] < time()) {
  1836. $this->dao->update(['uid' => $uid], ['is_money_level' => 0/*, 'overdue_time' => 0*/]);
  1837. return false;
  1838. }
  1839. return true;
  1840. }
  1841. /**
  1842. * @param array $where
  1843. * @return array
  1844. * @throws \think\db\exception\DataNotFoundException
  1845. * @throws \think\db\exception\DbException
  1846. * @throws \think\db\exception\ModelNotFoundException
  1847. */
  1848. public function getUserInfoList(array $where, $field = "*")
  1849. {
  1850. return $this->dao->getUserInfoList($where, $field);
  1851. }
  1852. /**
  1853. * 增加推广用户佣金
  1854. * @param int $uid
  1855. * @param int $spread_uid
  1856. * @param array $userInfo
  1857. * @param array $spread_user
  1858. * @return bool|mixed
  1859. * @throws \think\db\exception\DataNotFoundException
  1860. * @throws \think\db\exception\DbException
  1861. * @throws \think\db\exception\ModelNotFoundException
  1862. */
  1863. public function addBrokeragePrice(int $uid, int $spread_uid, array $userInfo = [], array $spread_user = [])
  1864. {
  1865. if (!$uid || !$spread_uid) {
  1866. return false;
  1867. }
  1868. //商城分销功能是否开启 0关闭1开启
  1869. if (!sys_config('brokerage_func_status')) return true;
  1870. if (!sys_config('brokerage_user_status')) return true;
  1871. //获取设置推广佣金单价
  1872. $brokerage_price = sys_config('uni_brokerage_price', 0);
  1873. //获取推广佣金当日限额
  1874. $day_brokerage_price_upper = sys_config('day_brokerage_price_upper', 0);
  1875. if (!floatval($brokerage_price) || !floatval($day_brokerage_price_upper)) {
  1876. return true;
  1877. }
  1878. if (!$userInfo) {
  1879. $userInfo = $this->getUserInfo($uid);
  1880. }
  1881. if (!$userInfo) {
  1882. return false;
  1883. }
  1884. if (!$spread_user) {
  1885. $spread_user = $this->dao->getOne(['uid' => $spread_uid, 'status' => 1]);
  1886. }
  1887. if (!$spread_user) {
  1888. return false;
  1889. }
  1890. if (!$this->checkUserPromoter($spread_uid, $spread_user)) {
  1891. return false;
  1892. }
  1893. /** @var UserBrokerageServices $userBrokerageServices */
  1894. $userBrokerageServices = app()->make(UserBrokerageServices::class);
  1895. // -1不限制
  1896. if ($day_brokerage_price_upper != -1) {
  1897. if ($day_brokerage_price_upper <= 0) {
  1898. return true;
  1899. } else {
  1900. //获取上级用户今日获取推广用户佣金
  1901. $spread_day_brokerage = $userBrokerageServices->getUserBrokerageSum($spread_uid, ['brokerage_user'], 'today');
  1902. //超过上限
  1903. if (($spread_day_brokerage + $brokerage_price) > $day_brokerage_price_upper) {
  1904. return true;
  1905. }
  1906. }
  1907. }
  1908. $spreadPrice = $spread_user['brokerage_price'];
  1909. // 上级推广员返佣之后的金额
  1910. $balance = bcadd($spreadPrice, $brokerage_price, 2);
  1911. return $this->transaction(function () use ($uid, $spread_uid, $brokerage_price, $userInfo, $balance, $userBrokerageServices) {
  1912. // 添加返佣记录
  1913. $res1 = $userBrokerageServices->income('get_user_brokerage', $spread_uid, [
  1914. 'nickname' => $userInfo['nickname'],
  1915. 'number' => floatval($brokerage_price)
  1916. ], $balance, $uid);
  1917. // 添加用户余额
  1918. $res2 = $this->dao->bcInc($spread_uid, 'brokerage_price', $brokerage_price, 'uid');
  1919. //给上级发送获得佣金的模板消息
  1920. /** @var StoreOrderTakeServices $storeOrderTakeServices */
  1921. $storeOrderTakeServices = app()->make(StoreOrderTakeServices::class);
  1922. $storeOrderTakeServices->sendBackOrderBrokerage([], $spread_uid, $brokerage_price, 'user');
  1923. return $res1 && $res2;
  1924. });
  1925. }
  1926. /**
  1927. * 获取上级uid
  1928. * @param int $uid
  1929. * @param array $userInfo
  1930. * @param bool $is_spread
  1931. * @return int|mixed
  1932. */
  1933. public function getSpreadUid(int $uid, $userInfo = [], $is_spread = true)
  1934. {
  1935. if (!$uid) {
  1936. return 0;
  1937. }
  1938. //商城分销功能是否开启 0关闭1开启
  1939. if (!sys_config('brokerage_func_status')) return -1;
  1940. if (!$userInfo) {
  1941. $userInfo = $this->getUserInfo($uid);
  1942. }
  1943. if (!$userInfo) {
  1944. return 0;
  1945. }
  1946. //上级的上级不需要检测自购
  1947. if ($is_spread) {
  1948. //开启自购
  1949. $is_self_brokerage = sys_config('is_self_brokerage', 0);
  1950. if ($is_self_brokerage && $is_spread) {
  1951. return $uid;
  1952. }
  1953. }
  1954. //绑定类型
  1955. $store_brokergae_binding_status = sys_config('store_brokerage_binding_status', 1);
  1956. if ($store_brokergae_binding_status == 1 || $store_brokergae_binding_status == 3) {
  1957. return $userInfo['spread_uid'];
  1958. }
  1959. //分销绑定类型为时间段且没过期
  1960. $store_brokerage_binding_time = sys_config('store_brokerage_binding_time', 30);
  1961. if ($store_brokergae_binding_status == 2 && ($userInfo['spread_time'] + $store_brokerage_binding_time * 24 * 3600) > time()) {
  1962. return $userInfo['spread_uid'];
  1963. }
  1964. return -1;
  1965. }
  1966. /**
  1967. * 获取事业部/代理/员工列表
  1968. * @param array $where
  1969. * @param string $field
  1970. * @return array
  1971. * @throws \think\db\exception\DataNotFoundException
  1972. * @throws \think\db\exception\DbException
  1973. * @throws \think\db\exception\ModelNotFoundException
  1974. */
  1975. public function getDivisionList(array $where = [], string $field = '*')
  1976. {
  1977. [$page, $limit] = $this->getPageValue();
  1978. $list = $this->dao->getList($where, $field, $page, $limit);
  1979. $count = $this->dao->count($where);
  1980. return compact('list', 'count');
  1981. }
  1982. /**
  1983. * 添加编辑用户信息时候的信息
  1984. * @param $uid
  1985. * @return array
  1986. * @throws \think\db\exception\DataNotFoundException
  1987. * @throws \think\db\exception\DbException
  1988. * @throws \think\db\exception\ModelNotFoundException
  1989. */
  1990. public function getUserSaveInfo($uid)
  1991. {
  1992. /** @var UserLabelServices $userLabelServices */
  1993. $userLabelServices = app()->make(UserLabelServices::class);
  1994. /** @var UserLabelRelationServices $userLabelRelationServices */
  1995. $userLabelRelationServices = app()->make(UserLabelRelationServices::class);
  1996. /** @var UserLabelCateServices $userLabelCateServices */
  1997. $userLabelCateServices = app()->make(UserLabelCateServices::class);
  1998. /** @var UserGroupServices $userGroupServices */
  1999. $userGroupServices = app()->make(UserGroupServices::class);
  2000. /** @var SystemUserLevelServices $systemUserLevelServices */
  2001. $systemUserLevelServices = app()->make(SystemUserLevelServices::class);
  2002. $userInfo = $this->dao->get($uid);
  2003. if ($userInfo) {
  2004. $label_ids = $userLabelRelationServices->getUserLabels($uid);
  2005. $userInfo['label_id'] = !empty($label_ids) ? $userLabelServices->getLabelList(['ids' => $label_ids], ['id', 'label_name']) : [];
  2006. $userInfo['birthday'] = date('Y-m-d', (int)$userInfo['birthday']);
  2007. }
  2008. $levelInfo = $systemUserLevelServices->getWhereLevelList([], 'id,name');
  2009. $groupInfo = $userGroupServices->getGroupList();
  2010. $labelInfo = $userLabelCateServices->getUserLabel($uid);
  2011. return compact('userInfo', 'levelInfo', 'groupInfo', 'labelInfo');
  2012. }
  2013. }