UserServices.php 100 KB

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