UserServices.php 97 KB

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