UserServices.php 100 KB

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