UserServices.php 80 KB

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