UserServices.php 105 KB

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