UserServices.php 75 KB

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