UserServices.php 95 KB

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