UserServices.php 99 KB

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