UserServices.php 100 KB

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