UserRepository.php 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163
  1. <?php
  2. namespace app\common\repositories\user;
  3. use app\common\dao\BaseDao;
  4. use app\common\dao\user\UserDao;
  5. use app\common\model\user\User;
  6. use app\common\model\user\UserGroup;
  7. use app\common\model\wechat\WechatUser;
  8. use app\common\repositories\BaseRepository;
  9. use app\common\repositories\store\coupon\StoreCouponRepository;
  10. use app\common\repositories\store\order\StoreOrderRepository;
  11. use app\common\repositories\system\attachment\AttachmentRepository;
  12. use app\common\repositories\wechat\RoutineQrcodeRepository;
  13. use ln\exceptions\AuthException;
  14. use ln\jobs\AutoUserPosterJob;
  15. use ln\jobs\SendNewPeopleCouponJob;
  16. use ln\jobs\UserBrokerageLevelJob;
  17. use ln\services\JwtTokenService;
  18. use ln\services\QrcodeService;
  19. use ln\services\UploadService;
  20. use ln\services\WechatService;
  21. use FormBuilder\Exception\FormBuilderException;
  22. use FormBuilder\Factory\Elm;
  23. use FormBuilder\Form;
  24. use Swoole\Coroutine;
  25. use Swoole\Coroutine\Channel;
  26. use think\exception\ValidateException;
  27. use think\facade\Queue;
  28. use think\model\Relation;
  29. use function GuzzleHttp\Psr7\str;
  30. use think\db\exception\DataNotFoundException;
  31. use think\db\exception\DbException;
  32. use think\db\exception\ModelNotFoundException;
  33. use think\facade\Cache;
  34. use think\facade\Config;
  35. use think\facade\Db;
  36. use think\facade\Route;
  37. use think\Model;
  38. /**
  39. * Class UserRepository
  40. * @package app\common\repositories\user
  41. * @author zfy
  42. * @day 2020-04-28
  43. * @mixin UserDao
  44. */
  45. class UserRepository extends BaseRepository
  46. {
  47. /**
  48. * UserRepository constructor.
  49. * @param UserDao $dao
  50. */
  51. public function __construct(UserDao $dao)
  52. {
  53. $this->dao = $dao;
  54. }
  55. public function promoter($uid)
  56. {
  57. return $this->dao->update($uid, ['is_promoter' => 1, 'promoter_time' => date('Y-m-d H:i:s')]);
  58. }
  59. /**
  60. * @param $id
  61. * @return Form
  62. * @throws DataNotFoundException
  63. * @throws DbException
  64. * @throws FormBuilderException
  65. * @throws ModelNotFoundException
  66. * @author zfy
  67. * @day 2020-05-09
  68. */
  69. public function userForm($id)
  70. {
  71. $user = $this->dao->get($id);
  72. $user['uid'] = (string)$user['uid'];
  73. return Elm::createForm(Route::buildUrl('systemUserUpdate', compact('id'))->build(), [
  74. Elm::input('uid', '会员 ID', '')->disabled(true)->required(true),
  75. Elm::input('real_name', '真实姓名'),
  76. Elm::input('phone', '手机号'),
  77. Elm::date('birthday', '生日'),
  78. Elm::input('card_id', '身份证'),
  79. Elm::input('addres', '用户地址'),
  80. Elm::textarea('mark', '备注'),
  81. Elm::select('group_id', '会员分组')->options(function () {
  82. $data = app()->make(UserGroupRepository::class)->allOptions();
  83. $options = [['value' => 0, 'label' => '请选择']];
  84. foreach ($data as $value => $label) {
  85. $options[] = compact('value', 'label');
  86. }
  87. return $options;
  88. }),
  89. Elm::selectMultiple('label_id', '会员标签')->options(function () {
  90. $data = app()->make(UserLabelRepository::class)->allOptions();
  91. $options = [];
  92. foreach ($data as $value => $label) {
  93. $value = (string)$value;
  94. $options[] = compact('value', 'label');
  95. }
  96. return $options;
  97. }),
  98. Elm::radio('is_promoter', '推广员', 1)->options([
  99. ['value' => 0, 'label' => '关闭'],
  100. ['value' => 1, 'label' => '开启'],
  101. ])->required()
  102. ])->setTitle('编辑')->formData($user->toArray());
  103. }
  104. /**
  105. * @param array $where
  106. * @param $page
  107. * @param $limit
  108. * @return array
  109. * @throws DataNotFoundException
  110. * @throws DbException
  111. * @throws ModelNotFoundException
  112. * @author zfy
  113. * @day 2020-05-07
  114. */
  115. public function getList(array $where, $page, $limit)
  116. {
  117. $query = $this->dao->search($where)->with(['spread' => function ($query) {
  118. $query->field('uid,nickname,spread_uid');
  119. }, 'group']);
  120. $make = app()->make(UserLabelRepository::class);
  121. $count = $query->count($this->dao->getPk());
  122. $list = $query->page($page, $limit)->select()->each(function ($item) use ($make) {
  123. return $item->label = count($item['label_id']) ? $make->labels($item['label_id']) : [];
  124. });
  125. return compact('count', 'list');
  126. }
  127. public function promoterCount()
  128. {
  129. $total = $this->dao->search(['is_promoter' => 1])
  130. ->field('sum(spread_count) as spread_count,sum(spread_pay_count) as spread_pay_count,sum(spread_pay_price) as spread_pay_price,count(uid) as total_user,sum(brokerage_price) as brokerage_price')->find();
  131. $total = $total ? $total->toArray() : ['spread_count' => 0, 'spread_pay_count' => 0, 'spread_pay_price' => 0, 'total_user' => 0, 'brokerage_price' => 0];
  132. $total['total_extract'] = app()->make(UserExtractRepository::class)->getTotalExtractPrice();
  133. return [
  134. [
  135. 'className' => 'el-icon-s-goods',
  136. 'count' => $total['total_user'] ?? 0,
  137. 'name' => '分销员人数(人)'
  138. ],
  139. [
  140. 'className' => 'el-icon-s-order',
  141. 'count' => $total['spread_count'] ?? 0,
  142. 'name' => '推广人数(人)'
  143. ],
  144. [
  145. 'className' => 'el-icon-s-cooperation',
  146. 'count' => (int)($total['spread_pay_count'] ?? 0),
  147. 'name' => '推广订单数'
  148. ],
  149. [
  150. 'className' => 'el-icon-s-cooperation',
  151. 'count' => (float)($total['spread_pay_price'] ?? 0),
  152. 'name' => '推广订单金额'
  153. ],
  154. [
  155. 'className' => 'el-icon-s-cooperation',
  156. 'count' => (float)($total['total_extract'] ?? 0),
  157. 'name' => '已提现金额(元)'
  158. ],
  159. [
  160. 'className' => 'el-icon-s-cooperation',
  161. 'count' => (float)($total['brokerage_price'] ?? 0),
  162. 'name' => '未提现金额(元)'
  163. ],
  164. ];
  165. }
  166. public function promoterList(array $where, $page, $limit)
  167. {
  168. $where['is_promoter'] = 1;
  169. $query = $this->dao->search($where)->with(['spread' => function ($query) {
  170. $query->field('uid,nickname,spread_uid');
  171. }, 'brokerage' => function ($query) {
  172. $query->field('brokerage_level,brokerage_name,brokerage_icon');
  173. }]);
  174. $count = $query->count($this->dao->getPk());
  175. $list = $query->page($page, $limit)->select()->toArray();
  176. if (count($list)) {
  177. $promoterInfo = app()->make(UserExtractRepository::class)->getPromoterInfo(array_column($list, 'uid'));
  178. if (count($promoterInfo)) {
  179. $promoterInfo = array_combine(array_column($promoterInfo, 'uid'), $promoterInfo);
  180. }
  181. foreach ($list as $k => $item) {
  182. $list[$k]['total_extract_price'] = $promoterInfo[$item['uid']]['total_price'] ?? 0;
  183. $list[$k]['total_extract_num'] = $promoterInfo[$item['uid']]['total_num'] ?? 0;
  184. $list[$k]['total_brokerage_price'] = (float)bcadd($item['brokerage_price'], $list[$k]['total_extract_num'], 2);
  185. }
  186. }
  187. return compact('list', 'count');
  188. }
  189. public function merList(string $keyword, $page, $limit)
  190. {
  191. $query = $this->dao->searchMerUser($keyword);
  192. $count = $query->count($this->dao->getPk());
  193. $list = $query->page($page, $limit)->setOption('field', [])->field('uid,nickname,avatar,user_type,sex')->select();
  194. return compact('count', 'list');
  195. }
  196. /**
  197. * @param $id
  198. * @return Form
  199. * @throws DataNotFoundException
  200. * @throws DbException
  201. * @throws ModelNotFoundException
  202. * @throws FormBuilderException
  203. * @author zfy
  204. * @day 2020-05-07
  205. */
  206. public function changeGroupForm($id)
  207. {
  208. $isArray = is_array($id);
  209. if (!$isArray)
  210. $user = $this->dao->get($id);
  211. /** @var UserGroupRepository $make */
  212. $data = app()->make(UserGroupRepository::class)->allOptions();
  213. return Elm::createForm(Route::buildUrl($isArray ? 'systemUserBatchChangeGroup' : 'systemUserChangeGroup', $isArray ? [] : compact('id'))->build(), [
  214. Elm::hidden('ids', $isArray ? $id : [$id]),
  215. Elm::select('group_id', '用户分组', $isArray ? '' : $user->group_id)->options(function () use ($data) {
  216. $options = [['label' => '不设置', 'value' => '0']];
  217. foreach ($data as $value => $label) {
  218. $options[] = compact('value', 'label');
  219. }
  220. return $options;
  221. })
  222. ])->setTitle('修改用户分组');
  223. }
  224. /**
  225. * @param $id
  226. * @return Form
  227. * @throws DataNotFoundException
  228. * @throws DbException
  229. * @throws ModelNotFoundException
  230. * @throws FormBuilderException
  231. * @author zfy
  232. * @day 2020-05-07
  233. */
  234. public function changeLabelForm($id)
  235. {
  236. $isArray = is_array($id);
  237. if (!$isArray)
  238. $user = $this->dao->get($id);
  239. /** @var UserLabelRepository $make */
  240. $data = app()->make(UserLabelRepository::class)->allOptions();
  241. return Elm::createForm(Route::buildUrl($isArray ? 'systemUserBatchChangeLabel' : 'systemUserChangeLabel', $isArray ? [] : compact('id'))->build(), [
  242. Elm::hidden('ids', $isArray ? $id : [$id]),
  243. Elm::selectMultiple('label_id', '用户标签', $isArray ? [] : $user->label_id)->options(function () use ($data) {
  244. $options = [];
  245. foreach ($data as $value => $label) {
  246. $value = (string)$value;
  247. $options[] = compact('value', 'label');
  248. }
  249. return $options;
  250. })
  251. ])->setTitle('修改用户标签');
  252. }
  253. /**
  254. * @param $id
  255. * @return Form
  256. * @throws FormBuilderException
  257. * @author zfy
  258. * @day 2020-05-07
  259. */
  260. public function changeNowMoneyForm($id)
  261. {
  262. return Elm::createForm(Route::buildUrl('systemUserChangeNowMoney', compact('id'))->build(), [
  263. Elm::radio('type', '修改余额', 1)->options([
  264. ['label' => '增加', 'value' => 1],
  265. ['label' => '减少', 'value' => 0],
  266. ])->required(),
  267. Elm::number('now_money', '金额')->required()->min(0)
  268. ])->setTitle('修改用户余额');
  269. }
  270. public function changeIntegralForm($id)
  271. {
  272. return Elm::createForm(Route::buildUrl('systemUserChangeIntegral', compact('id'))->build(), [
  273. Elm::radio('type', '修改积分', 1)->options([
  274. ['label' => '增加', 'value' => 1],
  275. ['label' => '减少', 'value' => 0],
  276. ])->required(),
  277. Elm::number('now_money', '积分')->required()->min(0)
  278. ])->setTitle('修改用户积分');
  279. }
  280. /**
  281. * @param $id
  282. * @param $adminId
  283. * @param $type
  284. * @param $nowMoney
  285. * @throws DataNotFoundException
  286. * @throws DbException
  287. * @throws ModelNotFoundException
  288. * @author zfy
  289. * @day 2020-05-07
  290. */
  291. public function changeNowMoney($id, $adminId, $type, $nowMoney)
  292. {
  293. $user = $this->dao->get($id);
  294. Db::transaction(function () use ($id, $adminId, $user, $type, $nowMoney) {
  295. $balance = $type == 1 ? bcadd($user->now_money, $nowMoney, 2) : bcsub($user->now_money, $nowMoney, 2);
  296. $user->save(['now_money' => $balance]);
  297. /** @var UserBillRepository $make */
  298. $make = app()->make(UserBillRepository::class);
  299. if ($type == 1) {
  300. $make->incBill($id, 'now_money', 'sys_inc_money', [
  301. 'link_id' => $adminId,
  302. 'status' => 1,
  303. 'title' => '系统增加余额',
  304. 'number' => $nowMoney,
  305. 'mark' => '系统增加了' . floatval($nowMoney) . '余额',
  306. 'balance' => $balance
  307. ]);
  308. } else {
  309. $make->decBill($id, 'now_money', 'sys_dec_money', [
  310. 'link_id' => $adminId,
  311. 'status' => 1,
  312. 'title' => '系统减少余额',
  313. 'number' => $nowMoney,
  314. 'mark' => '系统减少了' . floatval($nowMoney) . '余额',
  315. 'balance' => $balance
  316. ]);
  317. }
  318. });
  319. }
  320. /**
  321. * @param $id
  322. * @param $adminId
  323. * @param $type
  324. * @param $integral
  325. * @throws DataNotFoundException
  326. * @throws DbException
  327. * @throws ModelNotFoundException
  328. * @author zfy
  329. * @day 2020-05-07
  330. */
  331. public function changeIntegral($id, $adminId, $type, $integral)
  332. {
  333. $user = $this->dao->get($id);
  334. Db::transaction(function () use ($id, $adminId, $user, $type, $integral) {
  335. $integral = (int)$integral;
  336. $balance = $type == 1 ? bcadd($user->integral, $integral, 0) : bcsub($user->integral, $integral, 0);
  337. $user->save(['integral' => $balance]);
  338. /** @var UserBillRepository $make */
  339. $make = app()->make(UserBillRepository::class);
  340. if ($type == 1) {
  341. $make->incBill($id, 'integral', 'sys_inc', [
  342. 'link_id' => $adminId,
  343. 'status' => 1,
  344. 'title' => '系统增加积分',
  345. 'number' => $integral,
  346. 'mark' => '系统增加了' . $integral . '积分',
  347. 'balance' => $balance
  348. ]);
  349. } else {
  350. $make->decBill($id, 'integral', 'sys_dec', [
  351. 'link_id' => $adminId,
  352. 'status' => 1,
  353. 'title' => '系统减少积分',
  354. 'number' => $integral,
  355. 'mark' => '系统减少了' . $integral . '积分',
  356. 'balance' => $balance
  357. ]);
  358. }
  359. });
  360. }
  361. /**
  362. * @param $password
  363. * @return false|string|null
  364. * @author zfy
  365. * @day 2020/6/22
  366. */
  367. public function encodePassword($password)
  368. {
  369. return password_hash($password, PASSWORD_BCRYPT);
  370. }
  371. /**
  372. * @param WechatUser $wechatUser
  373. * @return BaseDao|array|Model|null
  374. * @throws DataNotFoundException
  375. * @throws DbException
  376. * @throws ModelNotFoundException
  377. * @author zfy
  378. * @day 2020-04-28
  379. */
  380. public function syncWechatUser(WechatUser $wechatUser, $userType = 'wechat')
  381. {
  382. $user = $this->dao->wechatUserIdBytUser($wechatUser->wechat_user_id);
  383. $request = request();
  384. if ($user) {
  385. $user->save([
  386. 'nickname' => $wechatUser['nickname'] ?: '',
  387. 'avatar' => $wechatUser['headimgurl'] ?: '',
  388. 'sex' => $wechatUser['sex'] ?: 0,
  389. 'last_time' => date('Y-m-d H:i:s'),
  390. 'last_ip' => $request->ip(),
  391. ]);
  392. } else {
  393. $user = $this->create($userType, [
  394. 'account' => 'wx' . $wechatUser->wechat_user_id . time(),
  395. 'wechat_user_id' => $wechatUser->wechat_user_id,
  396. 'pwd' => $this->encodePassword($this->dao->defaultPwd()),
  397. 'nickname' => $wechatUser['nickname'] ?: '',
  398. 'avatar' => $wechatUser['headimgurl'] ?: '',
  399. 'sex' => $wechatUser['sex'] ?: 0,
  400. 'spread_uid' => 0,
  401. 'is_promoter' => 0,
  402. 'last_time' => date('Y-m-d H:i:s'),
  403. 'last_ip' => $request->ip()
  404. ]);
  405. }
  406. return $user;
  407. }
  408. /**
  409. * @param string $type
  410. * @param array $userInfo
  411. * @return BaseDao|Model
  412. * @author zfy
  413. * @day 2020-04-28
  414. */
  415. public function create(string $type, array $userInfo)
  416. {
  417. $userInfo['user_type'] = $type;
  418. $user = $this->dao->create($userInfo);
  419. try {
  420. Queue::push(SendNewPeopleCouponJob::class, $user->uid);
  421. } catch (\Exception $e) {
  422. }
  423. $user->isNew = true;
  424. return $user;
  425. }
  426. /**
  427. * @param User $user
  428. * @return array
  429. * @author zfy
  430. * @day 2020-04-29
  431. */
  432. public function createToken(User $user)
  433. {
  434. $service = new JwtTokenService();
  435. $exp = intval(Config::get('admin.user_token_valid_exp', 15));
  436. $token = $service->createToken($user->uid, 'user', strtotime("+ {$exp}day"));
  437. $this->cacheToken($token['token'], $token['out']);
  438. return $token;
  439. }
  440. /**
  441. * //TODO 登录成功后
  442. * @param User $user
  443. * @author zfy
  444. * @day 2020/6/22
  445. */
  446. public function loginAfter(User $user)
  447. {
  448. $user->last_time = date('Y-m-d H:i:s', time());
  449. $user->last_ip = request()->ip();
  450. $user->save();
  451. }
  452. /**
  453. * @param string $token
  454. * @param int $exp
  455. * @author zfy
  456. * @day 2020-04-29
  457. */
  458. public function cacheToken(string $token, int $exp)
  459. {
  460. Cache::store('file')->set('user_' . $token, time() + $exp, $exp);
  461. }
  462. /**
  463. * @param string $token
  464. * @author zfy
  465. * @day 2020-04-29
  466. */
  467. public function checkToken(string $token)
  468. {
  469. $cache = Cache::store('file');
  470. $has = $cache->has('user_' . $token);
  471. if (!$has)
  472. throw new AuthException('无效的token');
  473. $lastTime = $cache->get('user_' . $token);
  474. if (($lastTime + (intval($cache->get('admin.user_token_valid_exp', 15))) * 24 * 60 * 60) < time())
  475. throw new AuthException('token 已过期');
  476. }
  477. /**
  478. * @param string $token
  479. * @author zfy
  480. * @day 2020-04-29
  481. */
  482. public function updateToken(string $token)
  483. {
  484. Cache::store('file')->set('user_' . $token, time(), intval(Config::get('admin.user_token_valid_exp', 15)) * 24 * 60 * 60);
  485. }
  486. /**
  487. * @param string $token
  488. * @author zfy
  489. * @day 2020-04-29
  490. */
  491. public function clearToken(string $token)
  492. {
  493. Cache::delete('user_' . $token);
  494. }
  495. /**
  496. * @param string $key
  497. * @param string $code
  498. * @author zfy
  499. * @day 2020/6/1
  500. */
  501. public function checkCode(string $key, string $code)
  502. {
  503. $_code = Cache::get('am_captcha' . $key);
  504. if (!$_code) {
  505. throw new ValidateException('验证码过期');
  506. }
  507. if (strtolower($_code) != strtolower($code)) {
  508. throw new ValidateException('验证码错误');
  509. }
  510. //删除code
  511. Cache::delete('am_captcha' . $key);
  512. }
  513. /**
  514. * @param string $code
  515. * @return string
  516. * @author zfy
  517. * @day 2020/6/1
  518. */
  519. public function createLoginKey(string $code)
  520. {
  521. $key = uniqid(microtime(true), true);
  522. Cache::set('am_captcha' . $key, $code, Config::get('admin.captcha_exp', 5) * 60);
  523. return $key;
  524. }
  525. public function registr(string $phone, ?string $pwd, $user_type = 'h5')
  526. {
  527. $pwd = $pwd ? $this->encodePassword($pwd) : $this->encodePassword($this->dao->defaultPwd());
  528. $data = [
  529. 'account' => $phone,
  530. 'pwd' => $pwd,
  531. 'nickname' => substr($phone, 0, 3) . '****' . substr($phone, 7, 4),
  532. 'avatar' => '',
  533. 'phone' => $phone,
  534. 'last_ip' => app('request')->ip()
  535. ];
  536. return $this->create($user_type, $data);
  537. }
  538. public function routineSpreadImage(User $user)
  539. {
  540. //小程序
  541. $name = md5('surt' . $user['uid'] . $user['is_promoter'] . date('Ymd')) . '.jpg';
  542. $attachmentRepository = app()->make(AttachmentRepository::class);
  543. $imageInfo = $attachmentRepository->getWhere(['attachment_name' => $name]);
  544. $spreadBanner = systemGroupData('spread_banner');
  545. if (!count($spreadBanner)) return [];
  546. $siteName = systemConfig('site_name');
  547. $siteUrl = systemConfig('site_url');
  548. $uploadType = (int)systemConfig('upload_type') ?: 1;
  549. $urlCode = app()->make(QrcodeService::class)->getRoutineQrcodePath($name, 'pages/index/index', 'spid=' . $user['uid']);
  550. if (!$urlCode)
  551. throw new ValidateException('二维码生成失败');
  552. $filelink = [
  553. 'Bold' => 'public/font/Alibaba-PuHuiTi-Regular.otf',
  554. 'Normal' => 'public/font/Alibaba-PuHuiTi-Regular.otf',
  555. ];
  556. if (!file_exists($filelink['Bold'])) throw new ValidateException('缺少字体文件Bold');
  557. if (!file_exists($filelink['Normal'])) throw new ValidateException('缺少字体文件Normal');
  558. $resRoutine = true;
  559. foreach ($spreadBanner as $key => &$item) {
  560. $posterInfo = '海报生成失败:(';
  561. $config = array(
  562. 'image' => array(
  563. array(
  564. 'url' => $urlCode, //二维码资源
  565. 'stream' => 0,
  566. 'left' => 114,
  567. 'top' => 790,
  568. 'right' => 0,
  569. 'bottom' => 0,
  570. 'width' => 120,
  571. 'height' => 120,
  572. 'opacity' => 100
  573. )
  574. ),
  575. 'text' => array(
  576. array(
  577. 'text' => $user['nickname'],
  578. 'left' => 250,
  579. 'top' => 840,
  580. 'fontPath' => $filelink['Bold'], //字体文件
  581. 'fontSize' => 16, //字号
  582. 'fontColor' => '40,40,40', //字体颜色
  583. 'angle' => 0,
  584. ),
  585. array(
  586. 'text' => '邀请您加入' . $siteName,
  587. 'left' => 250,
  588. 'top' => 880,
  589. 'fontPath' => $filelink['Normal'], //字体文件
  590. 'fontSize' => 16, //字号
  591. 'fontColor' => '40,40,40', //字体颜色
  592. 'angle' => 0,
  593. )
  594. ),
  595. 'background' => $item['pic']
  596. );
  597. $resRoutine = $resRoutine && $posterInfo = setSharePoster($config, 'routine/spread/poster');
  598. if (!is_array($posterInfo)) throw new ValidateException($posterInfo);
  599. $posterInfo['dir'] = tidy_url($posterInfo['dir'], 0, $siteUrl);
  600. if ($resRoutine) {
  601. $attachmentRepository->create($uploadType, -1, $user->uid, [
  602. 'attachment_category_id' => 0,
  603. 'attachment_name' => $posterInfo['name'],
  604. 'attachment_src' => $posterInfo['dir']
  605. ]);
  606. $item['poster'] = $posterInfo['dir'];
  607. }
  608. }
  609. return $spreadBanner;
  610. }
  611. public function wxQrcode(User $user)
  612. {
  613. $name = md5('uwx_i' . $user['uid'] . date('Ymd')) . '.jpg';
  614. $key = 'home_' . $user['uid'];
  615. return app()->make(QrcodeService::class)->getWechatQrcodePath($name, rtrim(systemConfig('site_url'), '/') . '?spread=' . $user['uid'] . '&spid=' . $user['uid'], false, $key);
  616. }
  617. public function mpQrcode(User $user)
  618. {
  619. $name = md5('surt_i' . $user['uid'] . $user['is_promoter'] . date('Ymd')) . '.jpg';
  620. return app()->make(QrcodeService::class)->getRoutineQrcodePath($name, 'pages/index/index', 'spid=' . $user['uid']);
  621. }
  622. public function wxSpreadImage(User $user)
  623. {
  624. $name = md5('uwx' . $user['uid'] . $user['is_promoter'] . date('Ymd')) . '.jpg';
  625. $spreadBanner = systemGroupData('spread_banner');
  626. if (!count($spreadBanner)) return [];
  627. $siteName = systemConfig('site_name');
  628. $attachmentRepository = app()->make(AttachmentRepository::class);
  629. $imageInfo = $attachmentRepository->getWhere(['attachment_name' => $name]);
  630. $siteUrl = rtrim(systemConfig('site_url'), '/');
  631. $uploadType = (int)systemConfig('upload_type') ?: 1;
  632. $resWap = true;
  633. //检测远程文件是否存在
  634. if (isset($imageInfo['attachment_src']) && strstr($imageInfo['attachment_src'], 'http') !== false && curl_file_exist($imageInfo['attachment_src']) === false) {
  635. $imageInfo->delete();
  636. $imageInfo = null;
  637. }
  638. if (!$imageInfo) {
  639. $codeUrl = $siteUrl . '?spread=' . $user['uid'] . '&spid=' . $user['uid'];//二维码链接
  640. if (systemConfig('open_wechat_share')) {
  641. $qrcode = WechatService::create(false)->qrcodeService();
  642. $codeUrl = $qrcode->forever('_scan_url_home_' . $user['uid'])->url;
  643. }
  644. $imageInfo = app()->make(QrcodeService::class)->getQRCodePath($codeUrl, $name);
  645. if (is_string($imageInfo)) throw new ValidateException('二维码生成失败');
  646. $imageInfo['dir'] = tidy_url($imageInfo['dir'], null, $siteUrl);
  647. $attachmentRepository->create(systemConfig('upload_type') ?: 1, -1, $user->uid, [
  648. 'attachment_category_id' => 0,
  649. 'attachment_name' => $imageInfo['name'],
  650. 'attachment_src' => $imageInfo['dir']
  651. ]);
  652. $urlCode = $imageInfo['dir'];
  653. } else $urlCode = $imageInfo['attachment_src'];
  654. $filelink = [
  655. 'Bold' => 'public/font/Alibaba-PuHuiTi-Regular.otf',
  656. 'Normal' => 'public/font/Alibaba-PuHuiTi-Regular.otf',
  657. ];
  658. if (!file_exists($filelink['Bold'])) throw new ValidateException('缺少字体文件Bold');
  659. if (!file_exists($filelink['Normal'])) throw new ValidateException('缺少字体文件Normal');
  660. foreach ($spreadBanner as $key => &$item) {
  661. $posterInfo = '海报生成失败:(';
  662. $config = array(
  663. 'image' => array(
  664. array(
  665. 'url' => $urlCode, //二维码资源
  666. 'stream' => 0,
  667. 'left' => 114,
  668. 'top' => 790,
  669. 'right' => 0,
  670. 'bottom' => 0,
  671. 'width' => 120,
  672. 'height' => 120,
  673. 'opacity' => 100
  674. )
  675. ),
  676. 'text' => array(
  677. array(
  678. 'text' => $user['nickname'],
  679. 'left' => 250,
  680. 'top' => 840,
  681. 'fontPath' => $filelink['Bold'], //字体文件
  682. 'fontSize' => 16, //字号
  683. 'fontColor' => '40,40,40', //字体颜色
  684. 'angle' => 0,
  685. ),
  686. array(
  687. 'text' => '邀请您加入' . $siteName,
  688. 'left' => 250,
  689. 'top' => 880,
  690. 'fontPath' => $filelink['Normal'], //字体文件
  691. 'fontSize' => 16, //字号
  692. 'fontColor' => '40,40,40', //字体颜色
  693. 'angle' => 0,
  694. )
  695. ),
  696. 'background' => $item['pic']
  697. );
  698. $resWap = $resWap && $posterInfo = setSharePoster($config, 'wap/spread/poster');
  699. if (!is_array($posterInfo)) throw new ValidateException('海报生成失败');
  700. $posterInfo['dir'] = tidy_url($posterInfo['dir'], null, $siteUrl);
  701. $attachmentRepository->create($uploadType, -1, $user->uid, [
  702. 'attachment_category_id' => 0,
  703. 'attachment_name' => $posterInfo['name'],
  704. 'attachment_src' => $posterInfo['dir']
  705. ]);
  706. if ($resWap) {
  707. $item['wap_poster'] = $posterInfo['dir'];
  708. }
  709. }
  710. return $spreadBanner;
  711. }
  712. public function getUsername($uid)
  713. {
  714. return User::getDB()->where('uid', $uid)->value('nickname');
  715. }
  716. /**
  717. * @param $uid
  718. * @param $inc
  719. * @param string $type
  720. * @author zfy
  721. * @day 2020/6/22
  722. */
  723. public function incBrokerage($uid, $inc, $type = '+')
  724. {
  725. $weekKey = 'b_top_' . date('Y-m');
  726. $moneyKey = 'b_top_' . monday();
  727. //TODO 佣金周榜
  728. $brokerage = Cache::zscore($weekKey, $uid);
  729. $brokerage = $type == '+' ? bcadd($brokerage, $inc, 2) : bcsub($brokerage, $inc, 2);
  730. Cache::zadd($weekKey, $brokerage, $uid);
  731. //TODO 佣金月榜
  732. $brokerage = Cache::zscore($moneyKey, $uid);
  733. $brokerage = $type == '+' ? bcadd($brokerage, $inc, 2) : bcsub($brokerage, $inc, 2);
  734. Cache::zadd($moneyKey, $brokerage, $uid);
  735. }
  736. public function brokerageWeekTop($uid, $page, $limit)
  737. {
  738. $key = 'b_top_' . monday();
  739. return $this->topList($key, $page, $limit) + ['position' => $this->userPosition($key, $uid)];
  740. }
  741. public function brokerageMonthTop($uid, $page, $limit)
  742. {
  743. $key = 'b_top_' . date('Y-m');
  744. return $this->topList($key, $page, $limit) + ['position' => $this->userPosition($key, $uid)];
  745. }
  746. /**
  747. * //TODO 绑定上下级关系
  748. * @param User $user
  749. * @param int $spreadUid
  750. * @throws DbException
  751. * @author zfy
  752. * @day 2020/6/22
  753. */
  754. public function bindSpread(User $user, int $spreadUid)
  755. {
  756. if ($spreadUid && !$user->spread_uid && $user->uid != $spreadUid && ($spread = $this->dao->get($spreadUid)) && $spread->spread_uid != $user->uid) {
  757. $config = systemConfig(['extension_limit', 'extension_limit_day', 'integral_user_give']);
  758. Db::transaction(function () use ($spread, $spreadUid, $user, $config) {
  759. $user->spread_uid = $spreadUid;
  760. $user->spread_time = date('Y-m-d H:i:s');
  761. if ($config['extension_limit'] && $config['extension_limit_day']) {
  762. $user->spread_limit = date('Y-m-d H:i:s', strtotime('+ ' . $config['extension_limit_day'] . ' day'));
  763. }
  764. $spread->spread_count++;
  765. if ($config['integral_user_give'] > 0 && $user->isNew) {
  766. $integral = (int)$config['integral_user_give'];
  767. $spread->integral += $integral;
  768. app()->make(UserBillRepository::class)->incBill($spreadUid, 'integral', 'spread', [
  769. 'link_id' => $user->uid,
  770. 'status' => 1,
  771. 'title' => '邀请好友',
  772. 'number' => $integral,
  773. 'mark' => '邀请好友奖励' . $integral . '积分',
  774. 'balance' => $spread->integral
  775. ]);
  776. }
  777. $spread->save();
  778. $user->save();
  779. //TODO 推广人月榜
  780. Cache::zincrby('s_top_' . date('Y-m'), 1, $spreadUid);
  781. //TODO 推广人周榜
  782. Cache::zincrby('s_top_' . monday(), 1, $spreadUid);
  783. });
  784. Queue::push(UserBrokerageLevelJob::class, ['uid' => $spreadUid, 'type' => 'spread_user', 'inc' => 1]);
  785. }
  786. }
  787. public function userPosition($key, $uid)
  788. {
  789. $index = Cache::zrevrank($key, $uid);
  790. if ($index === false)
  791. return 0;
  792. else
  793. return $index + 1;
  794. }
  795. public function topList($key, $page, $limit)
  796. {
  797. $res = Cache::zrevrange($key, ($page - 1) * $limit, $limit, true);
  798. $ids = array_keys($res);
  799. $index = array_flip($ids);
  800. $count = Cache::zcard($key);
  801. $list = count($ids) ? $this->dao->users($ids, 'uid,avatar,nickname')->toArray() : [];
  802. foreach ($list as $k => $v) {
  803. $list[$k]['count'] = $res[$v['uid']] ?? 0;
  804. }
  805. $sort = array_column($list, 'count');
  806. array_multisort($sort, SORT_DESC, $list);
  807. return compact('count', 'list');
  808. }
  809. public function spreadWeekTop($page, $limit)
  810. {
  811. $key = 's_top_' . monday();
  812. return $this->topList($key, $page, $limit);
  813. }
  814. public function spreadMonthTop($page, $limit)
  815. {
  816. $key = 's_top_' . date('Y-m');
  817. return $this->topList($key, $page, $limit);
  818. }
  819. /**
  820. * @param $uid
  821. * @param $nickname
  822. * @param $sort
  823. * @param $page
  824. * @param $limit
  825. * @return array
  826. * @throws DataNotFoundException
  827. * @throws DbException
  828. * @throws ModelNotFoundException
  829. * @author zfy
  830. * @day 2020/6/22
  831. */
  832. public function getOneLevelList($uid, $nickname, $sort, $page, $limit)
  833. {
  834. $query = $this->search(['spread_uid' => $uid, 'nickname' => $nickname, 'sort' => $sort]);
  835. $count = $query->count();
  836. $list = $query->setOption('field', [])->field('uid,avatar,nickname,pay_count,pay_price,spread_count,spread_time')->page($page, $limit)->select();
  837. return compact('list', 'count');
  838. }
  839. /**
  840. * @param $uid
  841. * @param $nickname
  842. * @param $sort
  843. * @param $page
  844. * @param $limit
  845. * @return array
  846. * @throws DataNotFoundException
  847. * @throws DbException
  848. * @throws ModelNotFoundException
  849. * @author zfy
  850. * @day 2020/6/22
  851. */
  852. public function getTwoLevelList($uid, $nickname, $sort, $page, $limit)
  853. {
  854. $ids = $this->dao->getSubIds($uid);
  855. if (count($ids)) {
  856. $query = $this->search(['spread_uids' => $ids, 'nickname' => $nickname, 'sort' => $sort]);
  857. $count = $query->count();
  858. $list = $query->setOption('field', [])->field('uid,avatar,nickname,pay_count,pay_price,spread_count,spread_time')->page($page, $limit)->select();
  859. } else {
  860. $list = [];
  861. $count = 0;
  862. }
  863. return compact('list', 'count');
  864. }
  865. public function getLevelList($uid, array $where, $page, $limit)
  866. {
  867. if (!$where['level']) {
  868. $ids = $this->dao->getSubIds($uid);
  869. $ids[] = $uid;
  870. $where['spread_uids'] = $ids;
  871. } else if ($where['level'] == 2) {
  872. $ids = $this->dao->getSubIds($uid);
  873. if (!count($ids)) return ['list' => [], 'count' => 0];
  874. $where['spread_uids'] = $ids;
  875. } else {
  876. $where['spread_uid'] = $uid;
  877. }
  878. $query = $this->search($where);
  879. $count = $query->count();
  880. $list = $query->setOption('field', [])->field('uid,avatar,nickname,is_promoter,pay_count,pay_price,spread_count,create_time,spread_time,spread_limit')->page($page, $limit)->select();
  881. return compact('list', 'count');
  882. }
  883. /**
  884. * @param $uid
  885. * @param $page
  886. * @param $limit
  887. * @param array $where
  888. * @return array
  889. * @throws DataNotFoundException
  890. * @throws DbException
  891. * @throws ModelNotFoundException
  892. * @author zfy
  893. * @day 2020/6/26
  894. */
  895. public function subOrder($uid, $page, $limit, array $where = [])
  896. {
  897. if (isset($where['level'])) {
  898. if (!$where['level']) {
  899. $ids = $this->dao->getSubIds($uid);
  900. $subIds = $ids ? $this->dao->getSubAllIds($ids) : [];
  901. } else if ($where['level'] == 2) {
  902. $ids = $this->dao->getSubIds($uid);
  903. $subIds = $ids ? $this->dao->getSubAllIds($ids) : [];
  904. $ids = [];
  905. } else if ($where['level'] == -1) {
  906. $ids = [];
  907. $subIds = [];
  908. } else {
  909. $ids = $this->dao->getSubIds($uid);
  910. $subIds = [];
  911. }
  912. } else {
  913. $ids = $this->dao->getSubIds($uid);
  914. $subIds = $ids ? $this->dao->getSubAllIds($ids) : [];
  915. }
  916. $all = array_unique(array_merge($ids, $subIds));
  917. $all[] = -1;
  918. $query = app()->make(StoreOrderRepository::class)->usersOrderQuery($where, $all, (!isset($where['level']) || !$where['level'] || $where['level'] == -1) ? $uid : 0);
  919. $count = $query->count();
  920. $list = $query->page($page, $limit)->field('uid,order_sn,pay_time,extension_one,extension_two,is_selfbuy')->with(['user' => function ($query) {
  921. $query->field('avatar,nickname,uid');
  922. }])->select()->toArray();
  923. foreach ($list as $k => $item) {
  924. if ($item['is_selfbuy']) {
  925. if ($item['uid'] == $uid) {
  926. $list[$k]['brokerage'] = $item['extension_one'];
  927. } else if (in_array($item['uid'], $ids)) {
  928. $list[$k]['brokerage'] = $item['extension_two'];
  929. } else {
  930. $list[$k]['brokerage'] = 0;
  931. }
  932. } else {
  933. $list[$k]['brokerage'] = in_array($item['uid'], $ids) ? $item['extension_one'] : $item['extension_two'];
  934. }
  935. unset($list[$k]['extension_one'], $list[$k]['extension_two']);
  936. }
  937. return compact('count', 'list');
  938. }
  939. /**
  940. * @param User $user
  941. * @return User
  942. * @throws DataNotFoundException
  943. * @throws DbException
  944. * @throws ModelNotFoundException
  945. * @author zfy
  946. * @day 2020/7/2
  947. */
  948. public function mainUser(User $user): User
  949. {
  950. if (!$user->main_uid || $user->uid == $user->main_uid) return $user;
  951. $switchUser = $this->dao->get($user->main_uid);
  952. if (!$switchUser) return $user;
  953. if ($user->wechat_user_id && !$switchUser->wechat_user_id) {
  954. $switchUser->wechat_user_id = $user->wechat_user_id;
  955. $switchUser->save();
  956. }
  957. return $switchUser;
  958. }
  959. public function switchUser(User $user, $uid)
  960. {
  961. if ($user->uid == $uid || !$this->dao->existsWhere(['uid' => $uid, 'phone' => $user->phone]))
  962. throw new ValidateException('操作失败');
  963. $this->dao->update($user->uid, ['main_uid' => $uid]);
  964. $switchUser = $this->dao->get($uid);
  965. return $switchUser;
  966. }
  967. public function returnToken($user, $tokenInfo)
  968. {
  969. $user = $user->hidden(['label_id', 'group_id', 'main_uid', 'pwd', 'addres', 'card_id', 'last_time', 'last_ip', 'create_time', 'mark', 'status', 'spread_uid', 'spread_time', 'real_name', 'birthday', 'brokerage_price'])->toArray();
  970. return [
  971. 'token' => $tokenInfo['token'],
  972. 'exp' => $tokenInfo['out'],
  973. 'user' => $user
  974. ];
  975. }
  976. public function switchBrokerage(User $user, $brokerage)
  977. {
  978. $user->now_money = bcadd($user->now_money, $brokerage, 2);
  979. $user->brokerage_price = bcsub($user->brokerage_price, $brokerage, 2);
  980. Db::transaction(function () use ($brokerage, $user) {
  981. $user->save();
  982. app()->make(UserBillRepository::class)->incBill($user->uid, 'now_money', 'brokerage', [
  983. 'link_id' => 0,
  984. 'status' => 1,
  985. 'title' => '佣金转入余额',
  986. 'number' => $brokerage,
  987. 'mark' => '成功转入余额' . floatval($brokerage) . '元',
  988. 'balance' => $user->now_money
  989. ]);
  990. app()->make(UserBillRepository::class)->decBill($user->uid, 'brokerage', 'now_money', [
  991. 'link_id' => 0,
  992. 'status' => 1,
  993. 'title' => '佣金转入余额',
  994. 'number' => $brokerage,
  995. 'mark' => '成功转入余额' . floatval($brokerage) . '元',
  996. 'balance' => $user->brokerage_price
  997. ]);
  998. });
  999. }
  1000. public function rmLabel($id)
  1001. {
  1002. return $this->search(['label_id' => $id])->update([
  1003. 'label_id' => Db::raw('trim(BOTH \',\' FROM replace(CONCAT(\',\',label_id,\',\'),\',' . $id . ',\',\',\'))')
  1004. ]);
  1005. }
  1006. public function changeSpreadForm($id)
  1007. {
  1008. $user = $this->dao->get($id);
  1009. $form = Elm::createForm(Route::buildUrl('systemUserSpreadChange', compact('id'))->build(), [
  1010. [
  1011. 'type' => 'span',
  1012. 'title' => '用户昵称',
  1013. 'children' => [$user->nickname]
  1014. ], [
  1015. 'type' => 'span',
  1016. 'title' => '上级推荐人 Id',
  1017. 'children' => [$user->spread ? (string)$user->spread->uid : '无']
  1018. ], [
  1019. 'type' => 'span',
  1020. 'title' => '上级推荐人昵称',
  1021. 'children' => [$user->spread ? (string)$user->spread->nickname : '无']
  1022. ], Elm::frameImage('spid', '上级推荐人', '/' . config('admin.admin_prefix') . '/setting/referrerList?field=spid')->prop('srcKey', 'src')->value($user->spread ? [
  1023. 'src' => $user->spread->avatar,
  1024. 'id' => $user->spread->uid,
  1025. ] : [])->modal(['modal' => false])->width('896px')->height('480px'),
  1026. ]);
  1027. return $form->setTitle('修改推荐人');
  1028. }
  1029. public function changeSpread($uid, $spread_id, $admin = 0)
  1030. {
  1031. $spreadLogRepository = app()->make(UserSpreadLogRepository::class);
  1032. $user = $this->dao->get($uid);
  1033. if ($user->spread_uid == $spread_id)
  1034. return;
  1035. $config = systemConfig(['extension_limit', 'extension_limit_day']);
  1036. Db::transaction(function () use ($config, $user, $spreadLogRepository, $spread_id, $admin) {
  1037. $old = $user->spread_uid ?: 0;
  1038. $spreadLogRepository->add($user->uid, $spread_id, $old, $admin);
  1039. $user->spread_time = date('Y-m-d H:i:s');
  1040. if ($config['extension_limit'] && $config['extension_limit_day']) {
  1041. $user->spread_limit = date('Y-m-d H:i:s', strtotime('+ ' . $config['extension_limit_day'] . ' day'));
  1042. }
  1043. $user->spread_uid = $spread_id;
  1044. if ($spread_id) {
  1045. $this->dao->incSpreadCount($spread_id);
  1046. }
  1047. if ($old) {
  1048. $this->dao->decSpreadCount($old);
  1049. }
  1050. $user->save();
  1051. });
  1052. }
  1053. public function syncSpreadStatus()
  1054. {
  1055. if (systemConfig('extension_limit')) {
  1056. $this->dao->syncSpreadStatus();
  1057. }
  1058. }
  1059. /**
  1060. * TODO 积分增加
  1061. * @param int $uid
  1062. * @param int $number
  1063. * @param $title
  1064. * @param $type
  1065. * @param $data
  1066. * @author Qinii
  1067. * @day 6/9/21
  1068. */
  1069. public function incIntegral(int $uid,int $number,$title,$type,$data)
  1070. {
  1071. Db::transaction(function() use($uid,$number,$title,$type,$data){
  1072. $user = $this->dao->get($uid);
  1073. $user->integral = $user->integral + $number;
  1074. $user->save();
  1075. app()->make(UserBillRepository::class)
  1076. ->incBill($uid, 'integral', $type,
  1077. [
  1078. 'link_id' => 0,
  1079. 'status' => 1,
  1080. 'title' => $title,
  1081. 'number' => $data['number'],
  1082. 'mark' => $data['mark'],
  1083. 'balance' =>$data['balance'],
  1084. ]);
  1085. });
  1086. }
  1087. }