UserServices.php 104 KB

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