UserRepository.php 36 KB

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