UserServices.php 94 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324
  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.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. $spread_names = $this->dao->getColumn([['uid', 'in', array_unique(array_column($list, 'spread_uid'))]], 'nickname', 'uid');
  560. foreach ($list as &$item) {
  561. if (empty($item['addres'])) {
  562. if (!empty($item['country']) || !empty($item['province']) || !empty($item['city'])) {
  563. $item['addres'] = $item['country'] . $item['province'] . $item['city'];
  564. }
  565. }
  566. $item['status'] = ($item['status'] == 1) ? '正常' : '禁止';
  567. $item['birthday'] = $item['birthday'] ? date('Y-m-d', (int)$item['birthday']) : '';
  568. $item['extract_count_price'] = $userExtract[$item['uid']] ?? 0;//累计提现
  569. $item['spread_uid_nickname'] = $item['spread_uid'] ? ($spread_names[$item['spread_uid']] ?? '') . '/' . $item['spread_uid'] : '无';
  570. //用户类型
  571. if ($item['user_type'] == 'routine') {
  572. $item['user_type'] = '小程序';
  573. } else if ($item['user_type'] == 'wechat') {
  574. $item['user_type'] = '公众号';
  575. } else if ($item['user_type'] == 'h5') {
  576. $item['user_type'] = 'H5';
  577. } else if ($item['user_type'] == 'pc') {
  578. $item['user_type'] = 'PC';
  579. } else if ($item['user_type'] == 'app' || $item['user_type'] == 'apple') {
  580. $item['user_type'] = 'APP';
  581. } else $item['user_type'] = '其他';
  582. if ($item['sex'] == 1) {
  583. $item['sex'] = '男';
  584. } else if ($item['sex'] == 2) {
  585. $item['sex'] = '女';
  586. } else $item['sex'] = '保密';
  587. //等级名称
  588. $item['level'] = $levelName[$item['level']] ?? '无';
  589. //分组名称
  590. $item['group_id'] = $userGroup[$item['group_id']] ?? '无';
  591. //用户等级
  592. $item['vip_name'] = false;
  593. $levelinfo = $userLevel[$item['uid']] ?? null;
  594. if ($levelinfo) {
  595. if ($levelinfo && ($levelinfo['is_forever'] || time() < $levelinfo['valid_time'])) {
  596. $item['vip_name'] = $item['level'] != '无' ? $item['level'] : false;
  597. }
  598. }
  599. $item['labels'] = $userlabel[$item['uid']] ?? '';
  600. $item['isMember'] = $item['is_money_level'] > 0 ? 1 : 0;
  601. if (strpos($item['avatar'], '/statics/system_images/') !== false) {
  602. $item['avatar'] = set_file_url($item['avatar']);
  603. }
  604. }
  605. }
  606. return compact('count', 'list');
  607. }
  608. /**
  609. * 获取修改页面数据
  610. * @param int $id
  611. * @return array
  612. * @throws \FormBuilder\Exception\FormBuilderException
  613. */
  614. public function edit(int $id)
  615. {
  616. $user = $this->getUserInfo($id);
  617. if (!$user)
  618. throw new AdminException(100026);
  619. $f = array();
  620. $f[] = Form::input('uid', '用户编号', $user->getData('uid'))->disabled(true);
  621. $f[] = Form::input('real_name', '真实姓名', $user->getData('real_name'));
  622. $f[] = Form::input('phone', '手机号码', $user->getData('phone'));
  623. $f[] = Form::date('birthday', '生日', $user->getData('birthday') ? date('Y-m-d', $user->getData('birthday')) : '');
  624. $f[] = Form::input('card_id', '身份证号', $user->getData('card_id'));
  625. $f[] = Form::input('addres', '用户地址', $user->getData('addres'));
  626. $f[] = Form::textarea('mark', '用户备注', $user->getData('mark'));
  627. $f[] = Form::input('pwd', '登录密码')->type('password')->placeholder('不改密码请留空');
  628. $f[] = Form::input('true_pwd', '确认密码')->type('password')->placeholder('不改密码请留空');
  629. //查询高于当前会员的所有会员等级
  630. // $grade = app()->make(UserLevelServices::class)->getUerLevelInfoByUid($id, 'grade');
  631. $systemLevelList = app()->make(SystemUserLevelServices::class)->getWhereLevelList([], 'id,name');
  632. $setOptionLevel = function () use ($systemLevelList) {
  633. $menus = [];
  634. foreach ($systemLevelList as $menu) {
  635. $menus[] = ['value' => $menu['id'], 'label' => $menu['name']];
  636. }
  637. return $menus;
  638. };
  639. $f[] = Form::select('level', '用户等级', (int)$user->getData('level'))->setOptions(FormBuilder::setOptions($setOptionLevel))->filterable(true);
  640. $systemGroupList = app()->make(UserGroupServices::class)->getGroupList();
  641. $setOptionGroup = function () use ($systemGroupList) {
  642. $menus = [];
  643. foreach ($systemGroupList as $menu) {
  644. $menus[] = ['value' => $menu['id'], 'label' => $menu['group_name']];
  645. }
  646. return $menus;
  647. };
  648. $f[] = Form::select('group_id', '用户分组', $user->getData('group_id'))->setOptions(FormBuilder::setOptions($setOptionGroup))->filterable(true);
  649. $systemLabelList = app()->make(UserLabelServices::class)->getLabelList();
  650. $labels = app()->make(UserLabelRelationServices::class)->getUserLabels($user['uid']);
  651. $setOptionLabel = function () use ($systemLabelList) {
  652. $menus = [];
  653. foreach ($systemLabelList as $menu) {
  654. $menus[] = ['value' => $menu['id'], 'label' => $menu['label_name']];
  655. }
  656. return $menus;
  657. };
  658. $f[] = Form::select('label_id', '用户标签', $labels)->setOptions(FormBuilder::setOptions($setOptionLabel))->filterable(true)->multiple(true);
  659. $f[] = Form::radio('spread_open', '推广资格', $user->getData('spread_open'))->info('禁用用户的推广资格后,在任何分销模式下该用户都无分销权限')->options([['value' => 1, 'label' => '启用'], ['value' => 0, 'label' => '禁用']]);
  660. //分销模式 人人分销
  661. $storeBrokerageStatus = sys_config('store_brokerage_statu', 1);
  662. if ($storeBrokerageStatus == 1) {
  663. $f[] = Form::radio('is_promoter', '推广员权限', $user->getData('is_promoter'))->info('指定分销模式下,开启或关闭用户的推广权限')->options([['value' => 1, 'label' => '开启'], ['value' => 0, 'label' => '关闭']]);
  664. }
  665. $f[] = Form::radio('status', '用户状态', $user->getData('status'))->options([['value' => 1, 'label' => '开启'], ['value' => 0, 'label' => '锁定']]);
  666. return create_form('编辑', $f, Url::buildUrl('/user/user/' . $id), 'PUT');
  667. }
  668. /**
  669. * 添加用户表单
  670. * @param int $id
  671. * @return array
  672. * @throws \FormBuilder\Exception\FormBuilderException
  673. */
  674. public function saveForm()
  675. {
  676. $f = array();
  677. $f[] = Form::input('real_name', '真实姓名', '')->placeholder('请输入真实姓名');
  678. $f[] = Form::input('phone', '手机号码', '')->placeholder('请输入手机号码')->required();
  679. $f[] = Form::date('birthday', '生日', '')->placeholder('请选择生日');
  680. $f[] = Form::input('card_id', '身份证号', '')->placeholder('请输入身份证号');
  681. $f[] = Form::input('addres', '用户地址', '')->placeholder('请输入用户地址');
  682. $f[] = Form::textarea('mark', '用户备注', '')->placeholder('请输入用户备注');
  683. $f[] = Form::input('pwd', '登录密码')->type('password')->placeholder('请输入登录密码');
  684. $f[] = Form::input('true_pwd', '确认密码')->type('password')->placeholder('请再次确认密码');
  685. $systemLevelList = app()->make(SystemUserLevelServices::class)->getWhereLevelList([], 'id,name');
  686. $setOptionLevel = function () use ($systemLevelList) {
  687. $menus = [];
  688. foreach ($systemLevelList as $menu) {
  689. $menus[] = ['value' => $menu['id'], 'label' => $menu['name']];
  690. }
  691. return $menus;
  692. };
  693. $f[] = Form::select('level', '用户等级', '')->setOptions(FormBuilder::setOptions($setOptionLevel))->filterable(true);
  694. $systemGroupList = app()->make(UserGroupServices::class)->getGroupList();
  695. $setOptionGroup = function () use ($systemGroupList) {
  696. $menus = [];
  697. foreach ($systemGroupList as $menu) {
  698. $menus[] = ['value' => $menu['id'], 'label' => $menu['group_name']];
  699. }
  700. return $menus;
  701. };
  702. $f[] = Form::select('group_id', '用户分组', '')->setOptions(FormBuilder::setOptions($setOptionGroup))->filterable(true);
  703. $systemLabelList = app()->make(UserLabelServices::class)->getLabelList();
  704. $setOptionLabel = function () use ($systemLabelList) {
  705. $menus = [];
  706. foreach ($systemLabelList as $menu) {
  707. $menus[] = ['value' => $menu['id'], 'label' => $menu['label_name']];
  708. }
  709. return $menus;
  710. };
  711. $f[] = Form::select('label_id', '用户标签', '')->setOptions(FormBuilder::setOptions($setOptionLabel))->filterable(true)->multiple(true);
  712. $f[] = Form::radio('spread_open', '推广资格', 1)->info('禁用用户的推广资格后,在任何分销模式下该用户都无分销权限')->options([['value' => 1, 'label' => '启用'], ['value' => 0, 'label' => '禁用']]);
  713. //分销模式 人人分销
  714. $storeBrokerageStatus = sys_config('store_brokerage_statu', 1);
  715. if ($storeBrokerageStatus == 1) {
  716. $f[] = Form::radio('is_promoter', '推广员权限', 0)->info('指定分销模式下,开启或关闭用户的推广权限')->options([['value' => 1, 'label' => '开启'], ['value' => 0, 'label' => '关闭']]);
  717. }
  718. $f[] = Form::radio('status', '用户状态', 1)->options([['value' => 1, 'label' => '开启'], ['value' => 0, 'label' => '锁定']]);
  719. return create_form('添加用户', $f, $this->url('/user/user'), 'POST');
  720. }
  721. /**
  722. * 修改提交处理
  723. * @param int $id
  724. * @param array $data
  725. * @return bool
  726. * @throws Exception
  727. * @throws \think\db\exception\DataNotFoundException
  728. * @throws \think\db\exception\ModelNotFoundException
  729. */
  730. public function updateInfo(int $id, array $data)
  731. {
  732. $user = $this->getUserInfo($id);
  733. if (!$user) {
  734. throw new AdminException(100026);
  735. }
  736. $res1 = false;
  737. $res2 = false;
  738. $edit = array();
  739. if ($data['money_status'] && $data['money']) {//余额增加或者减少
  740. /** @var UserMoneyServices $userMoneyServices */
  741. $userMoneyServices = app()->make(UserMoneyServices::class);
  742. if ($data['money_status'] == 1) {//增加
  743. $edit['now_money'] = bcadd($user['now_money'], $data['money'], 2);
  744. $res1 = $userMoneyServices->income('system_add', $user['uid'], $data['money'], $edit['now_money'], $data['adminId'] ?? 0);
  745. //增加充值记录
  746. $recharge_data = [
  747. 'order_id' => app()->make(StoreOrderCreateServices::class)->getNewOrderId('cz'),
  748. 'uid' => $id,
  749. 'price' => $data['money'],
  750. 'recharge_type' => 'system',
  751. 'paid' => 1,
  752. 'add_time' => time(),
  753. 'give_price' => 0,
  754. 'channel_type' => 'system',
  755. 'pay_time' => time(),
  756. ];
  757. /** @var UserRechargeServices $rechargeServices */
  758. $rechargeServices = app()->make(UserRechargeServices::class);
  759. $rechargeServices->save($recharge_data);
  760. } else if ($data['money_status'] == 2) {//减少
  761. if ($user['now_money'] > $data['money']) {
  762. $edit['now_money'] = bcsub($user['now_money'], $data['money'], 2);
  763. } else {
  764. $edit['now_money'] = 0;
  765. $data['money'] = $user['now_money'];
  766. }
  767. $res1 = $userMoneyServices->income('system_sub', $user['uid'], $data['money'], $edit['now_money'], $data['adminId'] ?? 0);
  768. }
  769. event('OutPushListener', ['user_update_push', ['uid' => $id, 'type' => 'money', 'value' => $data['money_status'] == 2 ? -floatval($data['money']) : $data['money']]]);
  770. } else {
  771. $res1 = true;
  772. }
  773. if ($data['integration_status'] && $data['integration']) {//积分增加或者减少
  774. /** @var UserBillServices $userBill */
  775. $userBill = app()->make(UserBillServices::class);
  776. $integral_data = ['link_id' => $data['adminId'] ?? 0, 'number' => $data['integration']];
  777. if ($data['integration_status'] == 1) {//增加
  778. $edit['integral'] = bcadd($user['integral'], $data['integration'], 2);
  779. $integral_data['balance'] = $edit['integral'];
  780. $integral_data['title'] = '系统增加积分';
  781. $integral_data['mark'] = '系统增加了' . floatval($data['integration']) . '积分';
  782. $res2 = $userBill->incomeIntegral($user['uid'], 'system_add', $integral_data);
  783. } else if ($data['integration_status'] == 2) {//减少
  784. $edit['integral'] = bcsub($user['integral'], $data['integration'], 2);
  785. $integral_data['balance'] = $edit['integral'];
  786. $integral_data['title'] = '系统减少积分';
  787. $integral_data['mark'] = '系统扣除了' . floatval($data['integration']) . '积分';
  788. $res2 = $userBill->expendIntegral($user['uid'], 'system_sub', $integral_data);
  789. }
  790. event('OutPushListener', ['user_update_push', ['uid' => $id, 'type' => 'point', 'value' => $data['integration_status'] == 2 ? -intval($data['integration']) : $data['integration']]]);
  791. } else {
  792. $res2 = true;
  793. }
  794. //修改基本信息
  795. if (!isset($data['is_other']) || !$data['is_other']) {
  796. app()->make(UserLabelRelationServices::class)->setUserLable([$id], $data['label_id']);
  797. if (isset($data['pwd']) && $data['pwd'] && $data['pwd'] != $user['pwd']) {
  798. $edit['pwd'] = $data['pwd'];
  799. }
  800. if (isset($data['spread_open'])) {
  801. $edit['spread_open'] = $data['spread_open'];
  802. }
  803. $edit['status'] = $data['status'];
  804. $edit['real_name'] = $data['real_name'];
  805. $edit['card_id'] = $data['card_id'];
  806. $edit['birthday'] = strtotime($data['birthday']);
  807. $edit['mark'] = $data['mark'];
  808. $edit['is_promoter'] = $data['is_promoter'];
  809. $edit['level'] = $data['level'];
  810. $edit['phone'] = $data['phone'];
  811. $edit['addres'] = $data['addres'];
  812. $edit['group_id'] = $data['group_id'];
  813. if ($user['level'] != $data['level']) {
  814. /** @var UserLevelServices $userLevelService */
  815. $userLevelService = app()->make(UserLevelServices::class);
  816. $userLevelService->setUserLevel((int)$user['uid'], (int)$data['level']);
  817. }
  818. if ($data['is_promoter'] == 0) {
  819. app()->make(SpreadApplyServices::class)->delete(['uid' => $user['uid']]);
  820. }
  821. }
  822. if ($edit) $res3 = $this->dao->update($id, $edit);
  823. else $res3 = true;
  824. if ($res1 && $res2 && $res3)
  825. return true;
  826. else throw new AdminException(100007);
  827. }
  828. /**
  829. * 编辑其他
  830. * @param $id
  831. * @return mixed
  832. * @throws \FormBuilder\Exception\FormBuilderException
  833. */
  834. public function editOther($id, $type)
  835. {
  836. $user = $this->getUserInfo($id);
  837. if (!$user) {
  838. throw new AdminException(100026);
  839. }
  840. $f = array();
  841. if ($type == 'money') {
  842. $f[] = Form::radio('money_status', '修改余额', 1)->options([['value' => 1, 'label' => '增加'], ['value' => 2, 'label' => '减少']]);
  843. $f[] = Form::number('money', '余额', 0)->min(0)->max(999999.99);
  844. } else {
  845. $f[] = Form::radio('integration_status', '修改积分', 1)->options([['value' => 1, 'label' => '增加'], ['value' => 2, 'label' => '减少']]);
  846. $f[] = Form::number('integration', '积分', 0)->min(0)->precision(0)->max(999999);
  847. }
  848. return create_form('修改其他', $f, Url::buildUrl('/user/update_other/' . $id), 'PUT');
  849. }
  850. /**
  851. * 设置会员分组
  852. * @param $id
  853. * @return mixed
  854. */
  855. public function setGroup($uids)
  856. {
  857. /** @var UserGroupServices $groupServices */
  858. $groupServices = app()->make(UserGroupServices::class);
  859. $userGroup = $groupServices->getGroupList();
  860. if (count($uids) == 1) {
  861. $user = $this->getUserInfo($uids[0], ['group_id']);
  862. $setOptionUserGroup = function () use ($userGroup) {
  863. $menus = [];
  864. foreach ($userGroup as $menu) {
  865. $menus[] = ['value' => $menu['id'], 'label' => $menu['group_name']];
  866. }
  867. return $menus;
  868. };
  869. $field[] = Form::select('group_id', '用户分组', $user->getData('group_id') != 0 ? $user->getData('group_id') : '')->setOptions(FormBuilder::setOptions($setOptionUserGroup))->filterable(true);
  870. } else {
  871. $setOptionUserGroup = function () use ($userGroup) {
  872. $menus = [];
  873. foreach ($userGroup as $menu) {
  874. $menus[] = ['value' => $menu['id'], 'label' => $menu['group_name']];
  875. }
  876. return $menus;
  877. };
  878. $field[] = Form::select('group_id', '用户分组')->setOptions(FormBuilder::setOptions($setOptionUserGroup))->filterable(true);
  879. }
  880. $field[] = Form::hidden('uids', implode(',', $uids));
  881. return create_form('设置用户分组', $field, Url::buildUrl('/user/save_set_group'), 'PUT');
  882. }
  883. /**
  884. * 保存会员分组
  885. * @param $id
  886. * @return mixed
  887. */
  888. public function saveSetGroup($uids, int $group_id)
  889. {
  890. /** @var UserGroupServices $userGroup */
  891. $userGroup = app()->make(UserGroupServices::class);
  892. if (!$userGroup->getGroup($group_id)) {
  893. throw new AdminException(400696);
  894. }
  895. if (!$this->setUserGroup($uids, $group_id)) {
  896. throw new AdminException(400697);
  897. }
  898. return true;
  899. }
  900. /**
  901. * 设置用户标签
  902. * @param $uids
  903. * @return mixed
  904. */
  905. public function setLabel($uids)
  906. {
  907. /** @var UserLabelServices $labelServices */
  908. $labelServices = app()->make(UserLabelServices::class);
  909. $userLabel = $labelServices->getLabelList();
  910. if (count($uids) == 1) {
  911. $lids = app()->make(UserLabelRelationServices::class)->getUserLabels($uids[0]);
  912. $setOptionUserLabel = function () use ($userLabel) {
  913. $menus = [];
  914. foreach ($userLabel as $menu) {
  915. $menus[] = ['value' => $menu['id'], 'label' => $menu['label_name']];
  916. }
  917. return $menus;
  918. };
  919. $field[] = Form::select('label_id', '用户标签', $lids)->setOptions(FormBuilder::setOptions($setOptionUserLabel))->filterable(true)->multiple(true);
  920. } else {
  921. $setOptionUserLabel = function () use ($userLabel) {
  922. $menus = [];
  923. foreach ($userLabel as $menu) {
  924. $menus[] = ['value' => $menu['id'], 'label' => $menu['label_name']];
  925. }
  926. return $menus;
  927. };
  928. $field[] = Form::select('label_id', '用户标签')->setOptions(FormBuilder::setOptions($setOptionUserLabel))->filterable(true)->multiple(true);
  929. }
  930. $field[] = Form::hidden('uids', implode(',', $uids));
  931. return create_form('设置用户标签', $field, Url::buildUrl('/user/save_set_label'), 'PUT');
  932. }
  933. /**
  934. * 保存用户标签
  935. * @return mixed
  936. */
  937. public function saveSetLabel($uids, $lable_id)
  938. {
  939. foreach ($lable_id as $id) {
  940. if (!app()->make(UserLabelServices::class)->getLable((int)$id)) {
  941. throw new AdminException(400698);
  942. }
  943. }
  944. /** @var UserLabelRelationServices $services */
  945. $services = app()->make(UserLabelRelationServices::class);
  946. if (!$services->setUserLable($uids, $lable_id)) {
  947. throw new AdminException(400668);
  948. }
  949. return true;
  950. }
  951. /**
  952. * 赠送会员等级
  953. * @param int $uid
  954. * @return mixed
  955. * */
  956. public function giveLevel($id)
  957. {
  958. if (!$this->getUserInfo($id)) {
  959. throw new AdminException(400214);
  960. }
  961. //查询高于当前会员的所有会员等级
  962. $grade = app()->make(UserLevelServices::class)->getUerLevelInfoByUid($id, 'grade');
  963. $systemLevelList = app()->make(SystemUserLevelServices::class)->getWhereLevelList(['grade', '>', $grade ?? 0], 'id,name');
  964. $setOptionlevel = function () use ($systemLevelList) {
  965. $menus = [];
  966. foreach ($systemLevelList as $menu) {
  967. $menus[] = ['value' => $menu['id'], 'label' => $menu['name']];
  968. }
  969. return $menus;
  970. };
  971. $field[] = Form::select('level_id', '用户等级')->setOptions(FormBuilder::setOptions($setOptionlevel))->filterable(true);
  972. return create_form('赠送等级', $field, Url::buildUrl('/user/save_give_level/' . $id), 'PUT');
  973. }
  974. /**
  975. * 执行赠送会员等级
  976. * @param int $id
  977. * @param int $level_id
  978. * @return mixed
  979. * @throws \think\db\exception\DataNotFoundException
  980. * @throws \think\db\exception\DbException
  981. * @throws \think\db\exception\ModelNotFoundException
  982. */
  983. public function saveGiveLevel(int $id, int $level_id)
  984. {
  985. if (!$this->getUserInfo($id)) {
  986. throw new AdminException(400214);
  987. }
  988. /** @var SystemUserLevelServices $systemLevelServices */
  989. $systemLevelServices = app()->make(SystemUserLevelServices::class);
  990. /** @var UserLevelServices $userLevelServices */
  991. $userLevelServices = app()->make(UserLevelServices::class);
  992. //查询当前选择的会员等级
  993. $systemLevel = $systemLevelServices->getLevel($level_id);
  994. if (!$systemLevel) throw new AdminException(400699);
  995. //检查是否拥有此会员等级
  996. $level = $userLevelServices->getWhereLevel(['uid' => $id, 'level_id' => $level_id], 'valid_time,is_forever');
  997. if ($level && $level['status'] == 1 && $level['is_del'] == 0) {
  998. throw new AdminException(400700);
  999. }
  1000. //保存会员信息
  1001. if (!$userLevelServices->setUserLevel($id, $level_id, $systemLevel)) {
  1002. throw new AdminException(400219);
  1003. }
  1004. return true;
  1005. }
  1006. /**
  1007. * 赠送付费会员时长
  1008. * @param $id
  1009. * @return array
  1010. * @throws \FormBuilder\Exception\FormBuilderException
  1011. * @author 吴汐
  1012. * @email 442384644@qq.com
  1013. * @date 2023/03/01
  1014. */
  1015. public function giveLevelTime($id)
  1016. {
  1017. $userInfo = $this->getUserInfo($id);
  1018. if (!$userInfo) {
  1019. throw new AdminException(400214);
  1020. }
  1021. if ($userInfo['is_ever_level'] == 1) {
  1022. $timeDiff = '永久';
  1023. } else {
  1024. $timeDiff = $userInfo['overdue_time'] < time() ? '无' : date('Y-m-d H:i:s', $userInfo['overdue_time']);
  1025. }
  1026. $dayDiff = $userInfo['overdue_time'] > time() ? intval(($userInfo['overdue_time'] - time()) / 86400) : 0;
  1027. $field[] = Form::input('time_diff', '到期时间', $timeDiff)->readonly(true);
  1028. if ($userInfo['is_ever_level'] == 0) {
  1029. $field[] = Form::input('day_diff', '剩余天数', $dayDiff)->readonly(true);
  1030. $field[] = Form::number('days', '增加时长(天)')->precision(0)->required();
  1031. }
  1032. return create_form('赠送付费会员时长', $field, Url::buildUrl('/user/save_give_level_time/' . $id), 'PUT');
  1033. }
  1034. /**
  1035. * 执行赠送付费会员时长
  1036. * @param int $id
  1037. * @param int $days
  1038. * @return mixed
  1039. * @throws \think\db\exception\DataNotFoundException
  1040. * @throws \think\db\exception\DbException
  1041. * @throws \think\db\exception\ModelNotFoundException
  1042. */
  1043. public function saveGiveLevelTime(int $id, int $days)
  1044. {
  1045. $userInfo = $this->getUserInfo($id);
  1046. if ($userInfo->is_ever_level == 1) {
  1047. return true;
  1048. }
  1049. if (!$userInfo) {
  1050. throw new AdminException(400214);
  1051. }
  1052. if ($days == 0) throw new AdminException(400701);
  1053. if ($days < -1) throw new AdminException(400702);
  1054. if ($userInfo->is_money_level == 0) {
  1055. $userInfo->is_money_level = 3;
  1056. if ($days == -1) {
  1057. $userInfo->is_ever_level = 1;
  1058. $time = 0;
  1059. } else {
  1060. $userInfo->overdue_time = $time = time() + ($days * 86400);
  1061. }
  1062. } else {
  1063. if ($days == -1) {
  1064. $userInfo->is_ever_level = 1;
  1065. $time = 0;
  1066. } else {
  1067. $userInfo->overdue_time = $time = $userInfo->overdue_time + ($days * 86400);
  1068. }
  1069. }
  1070. $userInfo->save();
  1071. /** @var StoreOrderCreateServices $storeOrderCreateService */
  1072. $storeOrderCreateService = app()->make(StoreOrderCreateServices::class);
  1073. $orderInfo = [
  1074. 'uid' => $id,
  1075. 'order_id' => $storeOrderCreateService->getNewOrderId(),
  1076. 'type' => 3,
  1077. 'member_type' => 0,
  1078. 'pay_type' => 'admin',
  1079. 'paid' => 1,
  1080. 'pay_time' => time(),
  1081. 'is_free' => 1,
  1082. 'overdue_time' => $time,
  1083. 'vip_day' => $days,
  1084. 'add_time' => time()
  1085. ];
  1086. /** @var OtherOrderServices $otherOrder */
  1087. $otherOrder = app()->make(OtherOrderServices::class);
  1088. $otherOrder->save($orderInfo);
  1089. return true;
  1090. }
  1091. /**
  1092. * 清除会员等级
  1093. * @paran int $uid
  1094. * @paran boolean
  1095. * */
  1096. public function cleanUpLevel($uid)
  1097. {
  1098. if (!$this->getUserInfo($uid))
  1099. throw new AdminException(400214);
  1100. /** @var UserLevelServices $services */
  1101. $services = app()->make(UserLevelServices::class);
  1102. return $this->transaction(function () use ($uid, $services) {
  1103. $res = $services->delUserLevel($uid);
  1104. $res1 = $this->dao->update($uid, ['clean_time' => time(), 'level' => 0, 'exp' => 0], 'uid');
  1105. if (!$res && !$res1)
  1106. throw new AdminException(400186);
  1107. return true;
  1108. });
  1109. }
  1110. /**
  1111. * 用户详细信息
  1112. * @param int $uid
  1113. * @param array $userIfno
  1114. * @return array
  1115. * @throws \think\db\exception\DataNotFoundException
  1116. * @throws \think\db\exception\DbException
  1117. * @throws \think\db\exception\ModelNotFoundException
  1118. */
  1119. public function getUserDetailed(int $uid, $userIfno = [])
  1120. {
  1121. /** @var UserAddressServices $userAddress */
  1122. $userAddress = app()->make(UserAddressServices::class);
  1123. $field = 'real_name,phone,province,city,district,detail,post_code';
  1124. $address = $userAddress->getUserDefaultAddress($uid, $field);
  1125. if (!$address) {
  1126. $address = $userAddress->getUserAddressList($uid, $field);
  1127. $address = $address[0] ?? [];
  1128. }
  1129. $userInfo = $this->getUserInfo($uid);
  1130. return [
  1131. ['name' => '默认收货地址', 'value' => $address ? '收货人:' . $address['real_name'] . '邮编:' . $address['post_code'] . ' 收货人电话:' . $address['phone'] . ' 地址:' . $address['province'] . ' ' . $address['city'] . ' ' . $address['district'] . ' ' . $address['detail'] : ''],
  1132. ['name' => '手机号码', 'value' => $userInfo['phone']],
  1133. ['name' => '姓名', 'value' => ''],
  1134. ['name' => '微信昵称', 'value' => $userInfo['nickname']],
  1135. ['name' => '头像', 'value' => $userInfo['avatar']],
  1136. ['name' => '邮箱', 'value' => ''],
  1137. ['name' => '生日', 'value' => ''],
  1138. ['name' => '积分', 'value' => $userInfo['integral']],
  1139. ['name' => '上级推广人', 'value' => $userInfo['spread_uid'] ? $this->getUserInfo($userInfo['spread_uid'], ['nickname'])['nickname'] ?? '' : ''],
  1140. ['name' => '账户余额', 'value' => $userInfo['now_money']],
  1141. ['name' => '佣金总收入', 'value' => app()->make(UserBillServices::class)->getBrokerageSum($uid)],
  1142. ['name' => '提现总金额', 'value' => app()->make(UserExtractServices::class)->getUserExtract($uid)],
  1143. ];
  1144. }
  1145. /**
  1146. * 获取用户详情里面的用户消费能力和用户余额积分等
  1147. * @param $uid
  1148. * @return array[]
  1149. */
  1150. public function getHeaderList(int $uid, $userInfo = [])
  1151. {
  1152. if (!$userInfo) {
  1153. $userInfo = $this->getUserInfo($uid);
  1154. }
  1155. /** @var StoreOrderServices $orderServices */
  1156. $orderServices = app()->make(StoreOrderServices::class);
  1157. $where = ['uid' => $uid, 'paid' => 1, 'refund_status' => 0, 'pid' => 0];
  1158. return [
  1159. [
  1160. 'title' => '余额',
  1161. 'value' => $userInfo['now_money'] ?? 0,
  1162. 'key' => '元',
  1163. ],
  1164. [
  1165. 'title' => '总计订单',
  1166. 'value' => $orderServices->count($where),
  1167. 'key' => '笔',
  1168. ],
  1169. [
  1170. 'title' => '总消费金额',
  1171. 'value' => $orderServices->together($where, 'pay_price'),
  1172. 'key' => '元',
  1173. ],
  1174. [
  1175. 'title' => '积分',
  1176. 'value' => $userInfo['integral'] ?? 0,
  1177. 'key' => '',
  1178. ],
  1179. [
  1180. 'title' => '本月订单',
  1181. 'value' => $orderServices->count($where + ['time' => 'month']),
  1182. 'key' => '笔',
  1183. ],
  1184. [
  1185. 'title' => '本月消费金额',
  1186. 'value' => $orderServices->together($where + ['time' => 'month'], 'pay_price'),
  1187. 'key' => '元',
  1188. ]
  1189. ];
  1190. }
  1191. /**
  1192. * 获取用户记录里的积分总数和签到总数和余额变动总数
  1193. * @param $uid
  1194. * @return array
  1195. */
  1196. public function getUserBillCountData($uid)
  1197. {
  1198. /** @var UserBillServices $userBill */
  1199. $userBill = app()->make(UserBillServices::class);
  1200. $integral_count = $userBill->getIntegralCount($uid);
  1201. $sign_count = $userBill->getSignCount($uid);
  1202. $balanceChang_count = $userBill->getBrokerageCount($uid);
  1203. return [$integral_count, $sign_count, $balanceChang_count];
  1204. }
  1205. /**
  1206. * 用户详情
  1207. * @param int $uid
  1208. * @return array
  1209. * @throws \think\db\exception\DataNotFoundException
  1210. * @throws \think\db\exception\DbException
  1211. * @throws \think\db\exception\ModelNotFoundException
  1212. */
  1213. public function read(int $uid)
  1214. {
  1215. $userInfo = $this->getUserInfo($uid);
  1216. if (!$userInfo) {
  1217. throw new AdminException(100026);
  1218. }
  1219. $userInfo['avatar'] = strpos($userInfo['avatar'], 'http') === false ? (sys_config('site_url') . $userInfo['avatar']) : $userInfo['avatar'];
  1220. $userInfo['overdue_time'] = date('Y-m-d H:i:s', $userInfo['overdue_time']);
  1221. $userInfo['birthday'] = $userInfo['birthday'] < 0 ? 0 : $userInfo['birthday'];
  1222. if ($userInfo['addres'] == '') {
  1223. $defaultAddressInfo = app()->make(UserAddressServices::class)->getUserDefaultAddress($uid);
  1224. if ($defaultAddressInfo) {
  1225. $userInfo['addres'] = $defaultAddressInfo['province'] . $defaultAddressInfo['city'] . $defaultAddressInfo['district'] . $defaultAddressInfo['detail'];
  1226. } else {
  1227. $userInfo['addres'] = '';
  1228. }
  1229. }
  1230. $userInfo['vip_name'] = app()->make(SystemUserLevelServices::class)->value(['grade' => $userInfo['level']], 'name');
  1231. $userInfo['group_name'] = app()->make(UserGroupServices::class)->value(['id' => $userInfo['group_id']], 'group_name');
  1232. $userInfo['spread_uid_nickname'] = $this->dao->value(['uid' => $userInfo['spread_uid']], 'nickname') . '/' . $userInfo['spread_uid'];
  1233. $userInfo['label_list'] = implode(',', array_column(app()->make(UserLabelRelationServices::class)->getUserLabelList([$uid]), 'label_name'));
  1234. return [
  1235. 'uid' => $uid,
  1236. 'userinfo' => $this->getUserDetailed($uid, $userInfo),
  1237. 'headerList' => $this->getHeaderList($uid, $userInfo),
  1238. 'count' => $this->getUserBillCountData($uid),
  1239. 'ps_info' => $userInfo
  1240. ];
  1241. }
  1242. /**
  1243. * 获取好友
  1244. * @param int $id
  1245. * @param string $field
  1246. * @return array
  1247. * @throws \think\db\exception\DataNotFoundException
  1248. * @throws \think\db\exception\DbException
  1249. * @throws \think\db\exception\ModelNotFoundException
  1250. */
  1251. public function getFriendList(int $id, string $field = 'uid,nickname,level,add_time,spread_time')
  1252. {
  1253. [$page, $limit] = $this->getPageValue();
  1254. $list = $this->dao->getList(['spread_uid' => $id], $field, $page, $limit);
  1255. /** @var SystemUserLevelServices $systemLevelServices */
  1256. $systemLevelServices = app()->make(SystemUserLevelServices::class);
  1257. $systemLevelList = $systemLevelServices->getWhereLevelList([], 'id,name');
  1258. if ($systemLevelServices) $systemLevelServices = array_combine(array_column($systemLevelList, 'id'), $systemLevelList);
  1259. foreach ($list as &$item) {
  1260. $item['type'] = $systemLevelServices[$item['level']]['name'] ?? '暂无';
  1261. $item['add_time'] = $item['spread_time'] && is_numeric($item['spread_time']) ? date('Y-m-d H:i:s', $item['spread_time']) : '';
  1262. }
  1263. $count = $this->dao->count(['spread_uid' => $id]);
  1264. return compact('list', 'count');
  1265. }
  1266. /**
  1267. * 获取单个用户信息
  1268. * @param $id 用户id
  1269. * @return mixed
  1270. */
  1271. public function oneUserInfo(int $id, string $type)
  1272. {
  1273. switch ($type) {
  1274. case 'spread':
  1275. // /** @var UserFriendsServices $services */
  1276. // $services = app()->make(UserFriendsServices::class);
  1277. // return $services->getFriendList(['uid' => $id], ['level', 'nickname']);
  1278. return $this->getFriendList($id);
  1279. case 'order':
  1280. /** @var StoreOrderServices $services */
  1281. $services = app()->make(StoreOrderServices::class);
  1282. return $services->getUserOrderList($id);
  1283. case 'integral':
  1284. /** @var UserBillServices $services */
  1285. $services = app()->make(UserBillServices::class);
  1286. return $services->getIntegralList($id, [], 'title,number,balance,mark,add_time,frozen_time,pm');
  1287. case 'sign':
  1288. /** @var UserBillServices $services */
  1289. $services = app()->make(UserBillServices::class);
  1290. return $services->getSignList($id, [], 'title,number,mark,add_time');
  1291. case 'coupon':
  1292. /** @var StoreCouponUserServices $services */
  1293. $services = app()->make(StoreCouponUserServices::class);
  1294. return $services->getUserCouponList($id);
  1295. case 'balance_change':
  1296. /** @var UserMoneyServices $services */
  1297. $services = app()->make(UserMoneyServices::class);
  1298. return $services->balanceList(['uid' => $id]);
  1299. default:
  1300. throw new AdminException(100100);
  1301. }
  1302. }
  1303. /**获取特定时间用户访问量
  1304. * @param $time
  1305. * @param $week
  1306. * @return int
  1307. */
  1308. public function todayLastVisits($time, $week)
  1309. {
  1310. return $this->dao->todayLastVisit($time, $week);
  1311. }
  1312. /**获取特定时间新增用户
  1313. * @param $time
  1314. * @param $week
  1315. * @return int
  1316. */
  1317. public function todayAddVisits($time, $week)
  1318. {
  1319. return $this->dao->todayAddVisit($time, $week);
  1320. }
  1321. /**
  1322. * 用户图表
  1323. */
  1324. public function userChart()
  1325. {
  1326. $starday = date('Y-m-d', strtotime('-30 day'));
  1327. $yesterday = date('Y-m-d', strtotime('+1 day'));
  1328. $user_list = $this->dao->userList($starday, $yesterday);
  1329. $chartdata = [];
  1330. $data = [];
  1331. $chartdata['legend'] = ['用户数'];//分类
  1332. $chartdata['yAxis']['maxnum'] = 0;//最大值数量
  1333. $chartdata['xAxis'] = [date('m-d')];//X轴值
  1334. $chartdata['series'] = [0];//分类1值
  1335. if (!empty($user_list)) {
  1336. foreach ($user_list as $k => $v) {
  1337. $data['day'][] = $v['day'];
  1338. $data['count'][] = $v['count'];
  1339. if ($chartdata['yAxis']['maxnum'] < $v['count'])
  1340. $chartdata['yAxis']['maxnum'] = $v['count'];
  1341. }
  1342. $chartdata['xAxis'] = $data['day'];//X轴值
  1343. $chartdata['series'] = $data['count'];//分类1值
  1344. }
  1345. $chartdata['bing_xdata'] = ['未消费用户', '消费一次用户', '留存客户', '回流客户'];
  1346. $color = ['#5cadff', '#b37feb', '#19be6b', '#ff9900'];
  1347. $pay[0] = $this->dao->count(['pay_count' => 0]);
  1348. $pay[1] = $this->dao->count(['pay_count' => 1]);
  1349. $pay[2] = $this->dao->userCount(1);
  1350. $pay[3] = $this->dao->userCount(2);
  1351. foreach ($pay as $key => $item) {
  1352. $bing_data[] = ['name' => $chartdata['bing_xdata'][$key], 'value' => $pay[$key], 'itemStyle' => ['color' => $color[$key]]];
  1353. }
  1354. $chartdata['bing_data'] = $bing_data;
  1355. return $chartdata;
  1356. }
  1357. /***********************************************/
  1358. /************ 前端api services *****************/
  1359. /***********************************************/
  1360. /**
  1361. * 用户信息
  1362. * @param $info
  1363. * @return mixed
  1364. */
  1365. public function userInfo($info)
  1366. {
  1367. /** @var UserBillServices $userBill */
  1368. $userBill = app()->make(UserBillServices::class);
  1369. $uid = (int)$info['uid'];
  1370. $broken_time = intval(sys_config('extract_time'));
  1371. $search_time = time() - 86400 * $broken_time;
  1372. //改造时间
  1373. $search_time = '1970/01/01' . ' - ' . date('Y/m/d H:i:s', $search_time);
  1374. //可提现佣金
  1375. //返佣 +
  1376. $brokerage_commission = (string)$userBill->getUsersBokerageSum(['uid' => $uid, 'pm' => 1], $search_time);
  1377. //退款退的佣金 -
  1378. $refund_commission = (string)$userBill->getUsersBokerageSum(['uid' => $uid, 'pm' => 0], $search_time);
  1379. $info['broken_commission'] = bcsub($brokerage_commission, $refund_commission, 2);
  1380. if ($info['broken_commission'] < 0)
  1381. $info['broken_commission'] = 0;
  1382. $info['commissionCount'] = bcsub($info['brokerage_price'], $info['broken_commission'], 2);
  1383. if ($info['commissionCount'] < 0)
  1384. $info['commissionCount'] = 0;
  1385. return $info;
  1386. }
  1387. /**
  1388. * 个人中心
  1389. * @param array $user
  1390. */
  1391. public function personalHome(array $user, $tokenData)
  1392. {
  1393. $userInfo = $user;
  1394. $uid = (int)$user['uid'];
  1395. /** @var StoreCouponUserServices $storeCoupon */
  1396. $storeCoupon = app()->make(StoreCouponUserServices::class);
  1397. /** @var UserBillServices $userBill */
  1398. $userBill = app()->make(UserBillServices::class);
  1399. /** @var UserExtractServices $userExtract */
  1400. $userExtract = app()->make(UserExtractServices::class);
  1401. /** @var StoreOrderServices $storeOrder */
  1402. $storeOrder = app()->make(StoreOrderServices::class);
  1403. /** @var UserLevelServices $userLevel */
  1404. $userLevel = app()->make(UserLevelServices::class);
  1405. /** @var StoreServiceServices $storeService */
  1406. $storeService = app()->make(StoreServiceServices::class);
  1407. /** @var WechatUserServices $wechatUser */
  1408. $wechatUser = app()->make(WechatUserServices::class);
  1409. /** @var UserInvoiceServices $userInvoice */
  1410. $userInvoice = app()->make(UserInvoiceServices::class);
  1411. /** @var MemberCardServices $memberCardService */
  1412. $memberCardService = app()->make(MemberCardServices::class);
  1413. /** @var StoreProductRelationServices $collect */
  1414. $collect = app()->make(StoreProductRelationServices::class);
  1415. /** @var MessageSystemServices $messageSystemServices */
  1416. $messageSystemServices = app()->make(MessageSystemServices::class);
  1417. /** @var DiyServices $diyServices */
  1418. $diyServices = app()->make(DiyServices::class);
  1419. /** @var AgentLevelServices $agentLevelServices */
  1420. $agentLevelServices = app()->make(AgentLevelServices::class);
  1421. //看付费会员是否开启
  1422. $isOpenMember = $memberCardService->isOpenMemberCard();
  1423. $user['is_open_member'] = $isOpenMember;
  1424. $user['agent_level_name'] = '';
  1425. if ($user['agent_level']) {
  1426. $levelInfo = $agentLevelServices->getLevelInfo((int)$user['agent_level'], 'id,name,status,grade');
  1427. if (!$levelInfo['status']) {
  1428. $levelInfo = $agentLevelServices->get([
  1429. ['grade', '<', $levelInfo['grade']],
  1430. ['is_del', '=', 0],
  1431. ['status', '=', 1]
  1432. ], ['id', 'name', 'status', 'grade']);
  1433. }
  1434. $user['agent_level_name'] = $levelInfo && $levelInfo['name'] && $levelInfo['status'] ? $levelInfo['name'] : '';
  1435. }
  1436. //会员领取优惠券
  1437. // $couponService->sendMemberCoupon($uid);
  1438. //看是否会员过期
  1439. $this->offMemberLevel($uid, $userInfo);
  1440. $wechatUserInfo = $wechatUser->getOne(['uid' => $uid, 'user_type' => $tokenData['type']]);
  1441. $user['is_complete'] = $wechatUserInfo['is_complete'] ?? 0;
  1442. $user['couponCount'] = $storeCoupon->getUserValidCouponCount((int)$uid);
  1443. $user['like'] = app()->make(StoreProductRelationServices::class)->getUserCollectCount($user['uid']);
  1444. $user['orderStatusNum'] = $storeOrder->getOrderData($uid);
  1445. $user['notice'] = 0;
  1446. /** @var UserMoneyServices $userMoney */
  1447. $userMoney = app()->make(UserMoneyServices::class);
  1448. $user['recharge'] = $userMoney->sum([
  1449. ['uid', '=', $uid], ['pm', '=', 1], ['type', 'in', ['recharge', 'system_add', 'extract', 'register_system_add', 'lottery_add']]
  1450. ], 'number');
  1451. $user['orderStatusSum'] = bcsub((string)$user['recharge'], (string)$user['now_money'], 2);
  1452. $user['extractTotalPrice'] = $userExtract->getExtractSum(['uid' => $uid, 'status' => 1]);//累计提现
  1453. $user['extractPrice'] = $user['brokerage_price'];//可提现
  1454. $user['statu'] = (int)sys_config('store_brokerage_statu');
  1455. if (!$user['is_promoter']) {
  1456. $price = $storeOrder->sum(['paid' => 1, 'refund_status' => 0, 'uid' => $user['uid']], 'pay_price');
  1457. if (is_brokerage_statu($price)) {
  1458. $this->dao->update($uid, ['is_promoter' => 1], 'uid');
  1459. $user['is_promoter'] = 1;
  1460. }
  1461. }
  1462. /** @var UserBrokerageServices $frozenPrices */
  1463. $frozenPrices = app()->make(UserBrokerageServices::class);
  1464. $user['broken_commission'] = $frozenPrices->getUserFrozenPrice($uid);
  1465. if ($user['broken_commission'] < 0)
  1466. $user['broken_commission'] = 0;
  1467. $user['commissionCount'] = bcsub((string)$user['brokerage_price'], (string)$user['broken_commission'], 2);
  1468. if ($user['commissionCount'] < 0)
  1469. $user['commissionCount'] = 0;
  1470. if (!sys_config('member_func_status'))
  1471. $user['vip'] = false;
  1472. else {
  1473. $userLevel = $userLevel->getUerLevelInfoByUid($user['uid']);
  1474. $user['vip'] = (bool)$userLevel;
  1475. if ($user['vip']) {
  1476. $user['vip_id'] = $userLevel['id'] ?? 0;
  1477. $user['vip_icon'] = set_file_url($userLevel['icon']) ?? '';
  1478. $user['vip_name'] = $userLevel['name'] ?? '';
  1479. }
  1480. }
  1481. $user['yesterDay'] = $frozenPrices->getUsersBokerageSum(['uid' => $uid, 'pm' => 1], 'yesterday');
  1482. $user['recharge_switch'] = (int)sys_config('recharge_switch');//充值开关
  1483. $user['adminid'] = $storeService->checkoutIsService(['uid' => $uid, 'status' => 1, 'customer' => 1]);
  1484. if ($user['phone'] && $user['user_type'] != 'h5') {
  1485. $user['switchUserInfo'][] = $userInfo;
  1486. $h5UserInfo = $this->dao->getOne(['account' => $user['phone'], 'user_type' => 'h5']);
  1487. if ($h5UserInfo) {
  1488. $user['switchUserInfo'][] = $h5UserInfo;
  1489. }
  1490. } else if ($user['phone'] && $user['user_type'] == 'h5') {
  1491. $wechatUserInfo = $this->getOne([['phone', '=', $user['phone']], ['user_type', '<>', 'h5']]);
  1492. if ($wechatUserInfo) {
  1493. $user['switchUserInfo'][] = $wechatUserInfo;
  1494. }
  1495. $user['switchUserInfo'][] = $userInfo;
  1496. } else if (!$user['phone']) {
  1497. $user['switchUserInfo'][] = $userInfo;
  1498. }
  1499. $user['broken_day'] = (int)sys_config('extract_time');//佣金冻结时间
  1500. $user['balance_func_status'] = (int)sys_config('balance_func_status', 0);
  1501. $invoice_func = $userInvoice->invoiceFuncStatus();
  1502. $user['invioce_func'] = $invoice_func['invoice_func'];
  1503. $user['special_invoice'] = $invoice_func['special_invoice'];
  1504. $user['collectCount'] = $collect->count(['uid' => $uid]);
  1505. $user['spread_status'] = $this->checkUserPromoter($user['uid']);
  1506. $user['pay_vip_status'] = $user['is_ever_level'] || ($user['is_money_level'] && $user['overdue_time'] > time());
  1507. $user['member_style'] = (int)$diyServices->getColorChange('member');
  1508. if ($user['is_ever_level']) {
  1509. $user['vip_status'] = 1;//永久会员
  1510. } else {
  1511. if (!$user['is_money_level'] && $user['overdue_time'] && $user['overdue_time'] < time()) {
  1512. $user['vip_status'] = -1;//开通过已过期
  1513. } else if (!$user['overdue_time'] && !$user['is_money_level']) {
  1514. $user['vip_status'] = 2;//没有开通过
  1515. } else if ($user['is_money_level'] && $user['overdue_time'] && $user['overdue_time'] > time()) {
  1516. $user['vip_status'] = 3;//开通了,没有到期
  1517. }
  1518. }
  1519. $user['svip_open'] = (bool)sys_config('member_card_status');
  1520. /** @var StoreServiceRecordServices $servicesRecord */
  1521. $servicesRecord = app()->make(StoreServiceRecordServices::class);
  1522. $service_num = $servicesRecord->sum(['user_id' => $uid], 'mssage_num');
  1523. $message = $messageSystemServices->count(['uid' => $uid, 'look' => 0, 'is_del' => 0]);
  1524. $user['service_num'] = $service_num + $message;
  1525. /** @var AgentLevelServices $userSpread */
  1526. $agentLevel = app()->make(AgentLevelServices::class);
  1527. $user['spread_level_count'] = $agentLevel->count(['status' => 1, 'is_del' => 0]);
  1528. $user['extract_type'] = sys_config('extract_type');
  1529. $user['integral'] = intval($user['integral']);
  1530. $user['is_agent_level'] = $agentLevelServices->count(['status' => 1, 'is_del' => 0]) > 0 ? 1 : 0;
  1531. $user['division_open'] = (int)sys_config('division_status', 0);
  1532. $user['agent_apply_open'] = (int)sys_config('agent_apply_open', 0);
  1533. $user['is_default_avatar'] = $user['avatar'] == sys_config('h5_avatar') ? 1 : 0;
  1534. $user['avatar'] = strpos($user['avatar'], '/statics/system_images/') !== false ? set_file_url($user['avatar']) : $user['avatar'];
  1535. $user['member_func_status'] = (int)sys_config('member_func_status');
  1536. $user['visit_num'] = app()->make(StoreProductLogServices::class)->getCountByUser($uid);
  1537. return $user;
  1538. }
  1539. /**
  1540. * 用户资金统计
  1541. * @param int $uid
  1542. */
  1543. public function balance(int $uid)
  1544. {
  1545. $userInfo = $this->getUserInfo($uid);
  1546. if (!$userInfo) {
  1547. throw new AdminException(400214);
  1548. }
  1549. /** @var UserBillServices $userBill */
  1550. $userBill = app()->make(UserBillServices::class);
  1551. /** @var StoreOrderServices $storeOrder */
  1552. $storeOrder = app()->make(StoreOrderServices::class);
  1553. $user['now_money'] = $userInfo['now_money'];//当前总资金
  1554. $user['recharge'] = $userBill->getRechargeSum($uid);//累计充值
  1555. $user['orderStatusSum'] = $storeOrder->sum(['uid' => $uid, 'paid' => 1, 'is_del' => 0], 'pay_price');//累计消费
  1556. return $user;
  1557. }
  1558. /**
  1559. * 用户修改信息
  1560. * @param Request $request
  1561. * @return mixed
  1562. */
  1563. public function eidtNickname(int $uid, array $data)
  1564. {
  1565. $info = $this->dao->get(['uid' => $uid]);
  1566. if (!$info) {
  1567. throw new ApiException(400214);
  1568. }
  1569. if (!$this->dao->update($uid, $data, 'uid')) {
  1570. throw new ApiException(100007);
  1571. }
  1572. //自定义事件-用户修改信息
  1573. event('CustomEventListener', ['user_change_info', [
  1574. 'uid' => $uid,
  1575. 'nickname' => $info['nickname'],
  1576. 'phone' => $info['phone'],
  1577. 'avatar' => $info['avatar'],
  1578. 'add_time' => date('Y-m-d H:i:s', $info['add_time']),
  1579. 'user_type' => $info['user_type'],
  1580. ]]);
  1581. return true;
  1582. }
  1583. /**
  1584. * 获取推广人排行
  1585. * @param $data 查询条件
  1586. * @return array
  1587. * @throws \think\db\exception\DataNotFoundException
  1588. * @throws \think\db\exception\ModelNotFoundException
  1589. * @throws \think\exception\DbException
  1590. */
  1591. public function getRankList(array $data)
  1592. {
  1593. $startTime = strtotime('this week Monday');
  1594. $endTime = time();
  1595. switch ($data['type']) {
  1596. case 'week':
  1597. $startTime = strtotime('this week Monday');
  1598. break;
  1599. case 'month':
  1600. $startTime = strtotime('last month');
  1601. break;
  1602. }
  1603. [$page, $limit] = $this->getPageValue();
  1604. $field = 't0.uid,t0.spread_uid,count(t1.spread_uid) AS count,t0.add_time,t0.nickname,t0.avatar';
  1605. return $this->dao->getAgentRankList([$startTime, $endTime], $field, $page, $limit);
  1606. }
  1607. /**
  1608. * 静默绑定推广人
  1609. * @param int $uid
  1610. * @param int $spreadUid
  1611. * @param $code
  1612. * @return bool
  1613. * @throws \think\db\exception\DataNotFoundException
  1614. * @throws \think\db\exception\DbException
  1615. * @throws \think\db\exception\ModelNotFoundException
  1616. */
  1617. public function spread(int $uid, int $spreadUid, $code, $agent_id)
  1618. {
  1619. $userInfo = $this->dao->getOne(['uid' => $uid]);
  1620. if (!$userInfo) {
  1621. throw new ApiException(100026);
  1622. }
  1623. if ($code && !$spreadUid) {
  1624. /** @var QrcodeServices $qrCode */
  1625. $qrCode = app()->make(QrcodeServices::class);
  1626. if ($info = $qrCode->getOne(['id' => $code, 'status' => 1])) {
  1627. if ($info['third_type'] == 'agent') {
  1628. $agent_id = $info['third_id'];
  1629. } else {
  1630. $spreadUid = $info['third_id'];
  1631. }
  1632. }
  1633. }
  1634. if ($agent_id) {
  1635. $spreadInfo = $this->dao->getOne(['uid' => $agent_id]);
  1636. if ($agent_id == $uid) {
  1637. return '自己不能推荐自己';
  1638. } else if (!$userInfo) {
  1639. return '用户不存在';
  1640. } else if (!$spreadInfo) {
  1641. return '上级用户不存在';
  1642. } else if ($userInfo->is_division) {
  1643. return '您是事业部,不能绑定成为别人的员工';
  1644. } else if ($userInfo->is_agent) {
  1645. return '您是代理商,不能绑定成为别人的员工';
  1646. } else if (app()->make(LoginServices::class)->updateUserInfo(['code' => $agent_id, 'is_staff' => 1], $userInfo, false)) {
  1647. return '绑定店员成功!';
  1648. }
  1649. }
  1650. if ($spreadUid == 0) return '不绑定';
  1651. $userSpreadUid = $this->dao->value(['uid' => $spreadUid], 'spread_uid');
  1652. //记录好友关系
  1653. if ($spreadUid && $uid && $spreadUid != $uid) {
  1654. /** @var UserFriendsServices $serviceFriend */
  1655. $serviceFriend = app()->make(UserFriendsServices::class);
  1656. $serviceFriend->saveFriend([
  1657. 'uid' => $uid,
  1658. 'friends_uid' => $spreadUid,
  1659. ]);
  1660. }
  1661. $check = false;
  1662. if (sys_config('brokerage_bindind') == 1) {
  1663. if (sys_config('store_brokerage_binding_status') == 1) {
  1664. if (!$userInfo['spread_uid']) {
  1665. $check = true;
  1666. }
  1667. } elseif (sys_config('store_brokerage_binding_status') == 2 && (($userInfo['spread_time'] + (sys_config('store_brokerage_binding_time') * 86400)) < time())) {
  1668. $check = true;
  1669. } elseif (sys_config('store_brokerage_binding_status') == 3) {
  1670. $check = true;
  1671. }
  1672. } elseif (sys_config('brokerage_bindind') == 2) {
  1673. if ($userInfo['add_time'] == $userInfo['last_time'] && $userInfo['spread_uid'] == 0) {
  1674. $check = true;
  1675. }
  1676. }
  1677. if ($userInfo['uid'] == $spreadUid || $userInfo['uid'] == $userSpreadUid) $check = false;
  1678. if ($check) {
  1679. $spreadInfo = $this->dao->get($spreadUid, ['division_id', 'agent_id', 'staff_id']);
  1680. $data = [];
  1681. $data['spread_uid'] = $spreadUid;
  1682. $data['spread_time'] = time();
  1683. $data['division_id'] = $spreadInfo['division_id'];
  1684. $data['agent_id'] = $spreadInfo['agent_id'];
  1685. $data['staff_id'] = $spreadInfo['staff_id'];
  1686. if (!$this->dao->update($uid, $data, 'uid')) {
  1687. throw new ApiException(410288);
  1688. }
  1689. return '绑定上级成功,上级uid为' . $spreadUid;
  1690. } else {
  1691. return '不绑定';
  1692. }
  1693. }
  1694. /**
  1695. * 添加访问记录
  1696. * @param Request $request
  1697. * @return mixed
  1698. */
  1699. public function setVisit(array $data)
  1700. {
  1701. $userInfo = $this->getUserInfo($data['uid'], 'uid,user_type');
  1702. if (!$userInfo) {
  1703. throw new ApiException(100026);
  1704. }
  1705. $data['channel_type'] = $userInfo['user_type'];
  1706. $data['add_time'] = time();
  1707. /** @var WechatUserServices $wechatUserServices */
  1708. $wechatUserServices = app()->make(WechatUserServices::class);
  1709. $wechatUser = $wechatUserServices->get(['uid' => $userInfo['uid'], 'user_type' => $userInfo['user_type']]);
  1710. if (!$wechatUser) {
  1711. $wechatUser = $wechatUserServices->get(['uid' => $userInfo['uid']]);
  1712. }
  1713. if ($wechatUser) {
  1714. $data['province'] = $wechatUser['province'];
  1715. }
  1716. /** @var UserVisitServices $userVisit */
  1717. $userVisit = app()->make(UserVisitServices::class);
  1718. if ($userVisit->save($data)) {
  1719. return true;
  1720. } else {
  1721. throw new ApiException(100015);
  1722. }
  1723. }
  1724. /**
  1725. * 获取活动状态
  1726. * @return mixed
  1727. */
  1728. public function activity()
  1729. {
  1730. /** @var StoreBargainServices $storeBragain */
  1731. $storeBragain = app()->make(StoreBargainServices::class);
  1732. /** @var StoreCombinationServices $storeCombinaion */
  1733. $storeCombinaion = app()->make(StoreCombinationServices::class);
  1734. /** @var StoreSeckillServices $storeSeckill */
  1735. $storeSeckill = app()->make(StoreSeckillServices::class);
  1736. $data['is_bargin'] = (bool)$storeBragain->validBargain();
  1737. $data['is_pink'] = (bool)$storeCombinaion->validCombination();
  1738. $data['is_seckill'] = (bool)$storeSeckill->getSeckillCount();
  1739. return $data;
  1740. }
  1741. /**
  1742. * 获取用户下级推广人
  1743. * @param int $uid 当前用户
  1744. * @param int $grade 等级 0 一级 1 二级
  1745. * @param string $orderBy 排序
  1746. * @param string $keyword
  1747. * @return array|bool
  1748. */
  1749. public function getUserSpreadGrade(int $uid = 0, $grade = 0, $orderBy = '', $keyword = '')
  1750. {
  1751. $user = $this->getUserInfo($uid);
  1752. if (!$user) {
  1753. throw new AdminException(400214);
  1754. }
  1755. $spread_one_ids = $this->getUserSpredadUids($uid, 1);
  1756. $spread_two_ids = $this->getUserSpredadUids($uid, 2);
  1757. $data = [
  1758. 'total' => count($spread_one_ids),
  1759. 'totalLevel' => count($spread_two_ids),
  1760. 'list' => []
  1761. ];
  1762. if (sys_config('brokerage_level', 2) == 1) {
  1763. $data['count'] = $data['total'];
  1764. } else {
  1765. $data['count'] = $data['total'] + $data['totalLevel'];
  1766. }
  1767. /** @var UserStoreOrderServices $userStoreOrder */
  1768. $userStoreOrder = app()->make(UserStoreOrderServices::class);
  1769. $list = [];
  1770. if ($grade == 0) {
  1771. if ($spread_one_ids) $list = $userStoreOrder->getUserSpreadCountList($spread_one_ids, $orderBy, $keyword);
  1772. } else {
  1773. if ($spread_two_ids) $list = $userStoreOrder->getUserSpreadCountList($spread_two_ids, $orderBy, $keyword);
  1774. }
  1775. foreach ($list as &$item) {
  1776. if (isset($item['spread_time']) && $item['spread_time']) {
  1777. $item['time'] = date('Y/m/d', $item['spread_time']);
  1778. }
  1779. }
  1780. $data['list'] = $list;
  1781. $data['brokerage_level'] = (int)sys_config('brokerage_level', 2);
  1782. return $data;
  1783. }
  1784. /**
  1785. * 获取推广人uids
  1786. * @param int $uid
  1787. * @param bool $one
  1788. * @return array
  1789. */
  1790. public function getUserSpredadUids(int $uid, int $type = 0)
  1791. {
  1792. $uids = $this->dao->getColumn(['spread_uid' => $uid, 'is_del' => 0], 'uid');
  1793. if ($type === 1) {
  1794. return $uids;
  1795. }
  1796. if ($uids) {
  1797. $uidsTwo = $this->dao->getColumn([['spread_uid', 'in', $uids], ['is_del', '=', 0]], 'uid');
  1798. if ($type === 2) {
  1799. return $uidsTwo;
  1800. }
  1801. if ($uidsTwo) {
  1802. $uids = array_merge($uids, $uidsTwo);
  1803. }
  1804. }
  1805. return $uids;
  1806. }
  1807. /**
  1808. * 检测用户是否是推广员
  1809. * @param int $uid
  1810. * @param $user
  1811. * @return bool
  1812. */
  1813. public function checkUserPromoter(int $uid, $user = [])
  1814. {
  1815. if (!$user) {
  1816. $user = $this->getUserInfo($uid, 'spread_open,is_promoter');
  1817. }
  1818. if (!$user) {
  1819. return false;
  1820. }
  1821. //分销是否开启
  1822. if (!sys_config('brokerage_func_status')) {
  1823. return false;
  1824. }
  1825. if (isset($user['spread_open']) && !$user['spread_open']) {
  1826. return false;
  1827. }
  1828. /** @var StoreOrderServices $storeOrder */
  1829. $storeOrder = app()->make(StoreOrderServices::class);
  1830. $sumPrice = $storeOrder->sum(['uid' => $uid, 'paid' => 1], 'pay_price');//累计消费
  1831. $store_brokerage_statu = sys_config('store_brokerage_statu');
  1832. $store_brokerage_price = sys_config('store_brokerage_price');
  1833. if ($user['is_promoter'] || $store_brokerage_statu == 2 || ($store_brokerage_statu == 3 && $sumPrice > $store_brokerage_price)) {
  1834. if (!$user['is_promoter']) {
  1835. $this->dao->update($uid, ['is_promoter' => 1]);
  1836. }
  1837. return true;
  1838. }
  1839. return false;
  1840. }
  1841. /**
  1842. * 同步微信粉丝用户(后台接口)
  1843. * @return bool
  1844. */
  1845. public function syncWechatUsers()
  1846. {
  1847. $appid = sys_config('wechat_appid');
  1848. $appSecret = sys_config('wechat_appsecret');
  1849. if (!$appid || !$appSecret) {
  1850. throw new AdminException(400236);
  1851. }
  1852. $key = md5('sync_wechat_users');
  1853. //一天点击一次
  1854. if (CacheService::get($key)) {
  1855. return true;
  1856. }
  1857. $next_openid = null;
  1858. do {
  1859. $result = WechatService::getUsersList($next_openid);
  1860. $userOpenids = $result['data'];
  1861. //拆分大数组
  1862. $opemidArr = array_chunk($userOpenids, 100);
  1863. foreach ($opemidArr as $openids) {
  1864. //加入同步|更新用户队列
  1865. UserJob::dispatch([$openids]);
  1866. }
  1867. $next_openid = $result['next_openid'];
  1868. } while ($next_openid != null);
  1869. CacheService::set($key, 1, 3600 * 24);
  1870. return true;
  1871. }
  1872. /**
  1873. * 导入微信粉丝用户
  1874. * @param array $openids
  1875. * @return bool
  1876. */
  1877. public function importUser(array $noBeOpenids)
  1878. {
  1879. if (!$noBeOpenids) {
  1880. return true;
  1881. }
  1882. $dataAll = $data = [];
  1883. $time = time();
  1884. foreach ($noBeOpenids as $openid) {
  1885. try {
  1886. $info = WechatService::getUserInfo($openid);
  1887. $info = is_object($info) ? $info->toArray() : $info;
  1888. } catch (\Throwable $e) {
  1889. $info = [];
  1890. }
  1891. if (!$info) continue;
  1892. $data['nickname'] = $info['nickname'] ?? '';
  1893. $data['headimgurl'] = $info['headimgurl'] ?? '';
  1894. $userInfoData = $this->setUserInfo($data);
  1895. if (!$userInfoData) {
  1896. throw new AdminException(400703);
  1897. }
  1898. $data['uid'] = $userInfoData['uid'];
  1899. $data['subscribe'] = $info['subscribe'] ?? 1;
  1900. $data['unionid'] = $info['unionid'] ?? '';
  1901. $data['openid'] = $info['openid'] ?? '';
  1902. $data['sex'] = $info['sex'] ?? 0;
  1903. $data['language'] = $info['language'] ?? '';
  1904. $data['city'] = $info['city'] ?? '';
  1905. $data['province'] = $info['province'] ?? '';
  1906. $data['country'] = $info['country'] ?? '';
  1907. $data['subscribe_time'] = $info['subscribe_time'] ?? '';
  1908. $data['groupid'] = $info['groupid'] ?? 0;
  1909. $data['remark'] = $info['remark'] ?? '';
  1910. $data['tagid_list'] = isset($info['tagid_list']) && $info['tagid_list'] ? implode(',', $info['tagid_list']) : '';
  1911. $data['add_time'] = $time;
  1912. $data['is_complete'] = 1;
  1913. $dataAll[] = $data;
  1914. }
  1915. if ($dataAll) {
  1916. /** @var WechatUserServices $wechatUser */
  1917. $wechatUser = app()->make(WechatUserServices::class);
  1918. if (!$wechatUser->saveAll($dataAll)) {
  1919. throw new AdminException(400703);
  1920. }
  1921. }
  1922. return true;
  1923. }
  1924. /** 修改会员的时间及是否会员状态
  1925. * @param int $vip_day 会员天数
  1926. * @param array $user_id 用户id
  1927. * @param int $is_money_level 会员来源途径
  1928. * @param bool $member_type 会员卡类型
  1929. * @return mixed
  1930. * @throws \think\db\exception\DataNotFoundException
  1931. * @throws \think\db\exception\DbException
  1932. * @throws \think\db\exception\ModelNotFoundException
  1933. */
  1934. public function setMemberOverdueTime($vip_day, int $user_id, int $is_money_level, $member_type = false)
  1935. {
  1936. if ($vip_day == 0) throw new ApiException(410289);
  1937. $user_info = $this->getUserInfo($user_id, 'is_money_level,overdue_time');
  1938. if (!$user_info) throw new ApiException(410032);
  1939. if (!$member_type) $member_type = "month";
  1940. if ($member_type == 'ever') {
  1941. $overdue_time = 0;
  1942. $is_ever_level = 1;
  1943. } else {
  1944. if ($user_info['is_money_level'] == 0) {
  1945. $overdue_time = bcadd(bcmul($vip_day, 86400, 0), time(), 0);
  1946. } else {
  1947. $overdue_time = bcadd(bcmul($vip_day, 86400, 0), $user_info['overdue_time'], 0);
  1948. }
  1949. $is_ever_level = 0;
  1950. }
  1951. $setData['overdue_time'] = $overdue_time;
  1952. $setData['is_ever_level'] = $is_ever_level;
  1953. $setData['is_money_level'] = $is_money_level ?: 0;
  1954. // if ($user_info['level'] == 0) $setData['level'] = 1;
  1955. return $this->dao->update(['uid' => $user_id], $setData);
  1956. }
  1957. /**
  1958. * 会员过期改变状态,变为普通会员
  1959. * @param $uid
  1960. * @param $userInfo
  1961. * @return bool
  1962. * @throws \think\db\exception\DataNotFoundException
  1963. * @throws \think\db\exception\DbException
  1964. * @throws \think\db\exception\ModelNotFoundException
  1965. */
  1966. public function offMemberLevel($uid, $userInfo = [])
  1967. {
  1968. if (!$uid) return false;
  1969. if (!$userInfo) {
  1970. $userInfo = $this->dao->get($uid, ['is_ever_level', 'is_money_level', 'overdue_time']);
  1971. }
  1972. if (!$userInfo) return false;
  1973. if ($userInfo['is_ever_level'] == 0 && $userInfo['is_money_level'] > 0 && $userInfo['overdue_time'] < time()) {
  1974. $this->dao->update(['uid' => $uid], ['is_money_level' => 0/*, 'overdue_time' => 0*/]);
  1975. return false;
  1976. }
  1977. return $userInfo;
  1978. }
  1979. /**
  1980. * @param array $where
  1981. * @return array
  1982. * @throws \think\db\exception\DataNotFoundException
  1983. * @throws \think\db\exception\DbException
  1984. * @throws \think\db\exception\ModelNotFoundException
  1985. */
  1986. public function getUserInfoList(array $where, $field = "*")
  1987. {
  1988. return $this->dao->getUserInfoList($where, $field);
  1989. }
  1990. /**
  1991. * 增加推广用户佣金
  1992. * @param int $uid
  1993. * @param int $spread_uid
  1994. * @param array $userInfo
  1995. * @param array $spread_user
  1996. * @return bool|mixed
  1997. * @throws \think\db\exception\DataNotFoundException
  1998. * @throws \think\db\exception\DbException
  1999. * @throws \think\db\exception\ModelNotFoundException
  2000. */
  2001. public function addBrokeragePrice(int $uid, int $spread_uid, array $userInfo = [], array $spread_user = [])
  2002. {
  2003. if (!$uid || !$spread_uid) {
  2004. return false;
  2005. }
  2006. //商城分销功能是否开启 0关闭1开启
  2007. if (!sys_config('brokerage_func_status')) return true;
  2008. if (!sys_config('brokerage_user_status')) return true;
  2009. //获取设置推广佣金单价
  2010. $brokerage_price = sys_config('uni_brokerage_price', 0);
  2011. //获取推广佣金当日限额
  2012. $day_brokerage_price_upper = sys_config('day_brokerage_price_upper', 0);
  2013. if (!floatval($brokerage_price) || !floatval($day_brokerage_price_upper)) {
  2014. return true;
  2015. }
  2016. if (!$userInfo) {
  2017. $userInfo = $this->getUserInfo($uid);
  2018. }
  2019. if (!$userInfo) {
  2020. return false;
  2021. }
  2022. //根据手机号码查询此用户注销过,不反推广佣金
  2023. if ($userInfo['phone'] != '' && $this->dao->getCount(['phone' => $userInfo['phone'], 'is_del' => 1])) {
  2024. return false;
  2025. }
  2026. //根据openid查询此用户注销过,不反推广佣金
  2027. $wechatUserServices = app()->make(WechatUserServices::class);
  2028. $openidArray = $wechatUserServices->getColumn(['uid' => $uid], 'openid', 'id');
  2029. if ($wechatUserServices->getCount([['openid', 'in', $openidArray], ['is_del', '=', 1]])) {
  2030. return false;
  2031. }
  2032. if (!$spread_user) {
  2033. $spread_user = $this->dao->getOne(['uid' => $spread_uid, 'status' => 1]);
  2034. }
  2035. if (!$spread_user) {
  2036. return false;
  2037. }
  2038. if (!$this->checkUserPromoter($spread_uid, $spread_user)) {
  2039. return false;
  2040. }
  2041. /** @var UserBrokerageServices $userBrokerageServices */
  2042. $userBrokerageServices = app()->make(UserBrokerageServices::class);
  2043. // -1不限制
  2044. if ($day_brokerage_price_upper != -1) {
  2045. if ($day_brokerage_price_upper <= 0) {
  2046. return true;
  2047. } else {
  2048. //获取上级用户今日获取推广用户佣金
  2049. $spread_day_brokerage = $userBrokerageServices->getUserBrokerageSum($spread_uid, ['brokerage_user'], 'today');
  2050. //超过上限
  2051. if (($spread_day_brokerage + $brokerage_price) > $day_brokerage_price_upper) {
  2052. return true;
  2053. }
  2054. }
  2055. }
  2056. $spreadPrice = $spread_user['brokerage_price'];
  2057. // 上级推广员返佣之后的金额
  2058. $balance = bcadd($spreadPrice, $brokerage_price, 2);
  2059. return $this->transaction(function () use ($uid, $spread_uid, $brokerage_price, $userInfo, $balance, $userBrokerageServices) {
  2060. // 添加返佣记录
  2061. $res1 = $userBrokerageServices->income('get_user_brokerage', $spread_uid, [
  2062. 'nickname' => $userInfo['nickname'],
  2063. 'number' => floatval($brokerage_price)
  2064. ], $balance, $uid);
  2065. // 添加用户余额
  2066. $res2 = $this->dao->bcInc($spread_uid, 'brokerage_price', $brokerage_price, 'uid');
  2067. //给上级发送获得佣金的模板消息
  2068. /** @var StoreOrderTakeServices $storeOrderTakeServices */
  2069. $storeOrderTakeServices = app()->make(StoreOrderTakeServices::class);
  2070. $storeOrderTakeServices->sendBackOrderBrokerage([], $spread_uid, $brokerage_price, 'user');
  2071. return $res1 && $res2;
  2072. });
  2073. }
  2074. /**
  2075. * 获取上级uid
  2076. * @param int $uid
  2077. * @param array $userInfo
  2078. * @param bool $is_spread
  2079. * @return int|mixed
  2080. */
  2081. public function getSpreadUid(int $uid, $userInfo = [], $is_spread = true)
  2082. {
  2083. if (!$uid) {
  2084. return 0;
  2085. }
  2086. //商城分销功能是否开启 0关闭1开启
  2087. if (!sys_config('brokerage_func_status')) return -1;
  2088. if (!$userInfo) {
  2089. $userInfo = $this->getUserInfo($uid);
  2090. }
  2091. if (!$userInfo) {
  2092. return 0;
  2093. }
  2094. //上级的上级不需要检测自购
  2095. if ($is_spread) {
  2096. //开启自购
  2097. $is_self_brokerage = sys_config('is_self_brokerage', 0);
  2098. if ($is_self_brokerage && $is_spread) {
  2099. return $uid;
  2100. }
  2101. }
  2102. //绑定类型
  2103. $store_brokergae_binding_status = sys_config('store_brokerage_binding_status', 1);
  2104. if ($store_brokergae_binding_status == 1 || $store_brokergae_binding_status == 3) {
  2105. return $userInfo['spread_uid'];
  2106. }
  2107. //分销绑定类型为时间段且没过期
  2108. $store_brokerage_binding_time = sys_config('store_brokerage_binding_time', 30);
  2109. if ($store_brokergae_binding_status == 2 && ($userInfo['spread_time'] + $store_brokerage_binding_time * 24 * 3600) > time()) {
  2110. return $userInfo['spread_uid'];
  2111. }
  2112. return -1;
  2113. }
  2114. /**
  2115. * 获取事业部/代理/员工列表
  2116. * @param array $where
  2117. * @param string $field
  2118. * @return array
  2119. * @throws \think\db\exception\DataNotFoundException
  2120. * @throws \think\db\exception\DbException
  2121. * @throws \think\db\exception\ModelNotFoundException
  2122. */
  2123. public function getDivisionList(array $where = [], string $field = '*')
  2124. {
  2125. [$page, $limit] = $this->getPageValue();
  2126. $list = $this->dao->getList($where, $field, $page, $limit);
  2127. $count = $this->dao->count($where);
  2128. return compact('list', 'count');
  2129. }
  2130. /**
  2131. * 添加编辑用户信息时候的信息
  2132. * @param $uid
  2133. * @return array
  2134. * @throws \think\db\exception\DataNotFoundException
  2135. * @throws \think\db\exception\DbException
  2136. * @throws \think\db\exception\ModelNotFoundException
  2137. */
  2138. public function getUserSaveInfo($uid)
  2139. {
  2140. /** @var UserLabelServices $userLabelServices */
  2141. $userLabelServices = app()->make(UserLabelServices::class);
  2142. /** @var UserLabelRelationServices $userLabelRelationServices */
  2143. $userLabelRelationServices = app()->make(UserLabelRelationServices::class);
  2144. /** @var UserLabelCateServices $userLabelCateServices */
  2145. $userLabelCateServices = app()->make(UserLabelCateServices::class);
  2146. /** @var UserGroupServices $userGroupServices */
  2147. $userGroupServices = app()->make(UserGroupServices::class);
  2148. /** @var SystemUserLevelServices $systemUserLevelServices */
  2149. $systemUserLevelServices = app()->make(SystemUserLevelServices::class);
  2150. $userInfo = $this->dao->get($uid);
  2151. if ($userInfo) {
  2152. $label_ids = $userLabelRelationServices->getUserLabels($uid);
  2153. $userInfo['label_id'] = !empty($label_ids) ? $userLabelServices->getLabelList(['ids' => $label_ids], ['id', 'label_name']) : [];
  2154. $userInfo['birthday'] = (int)$userInfo['birthday'] ? date('Y-m-d', (int)$userInfo['birthday']) : '';
  2155. $userInfo['level'] = $userInfo['level'] != 0 ? $userInfo['level'] : '';
  2156. $userInfo['group_id'] = $userInfo['group_id'] != 0 ? $userInfo['group_id'] : '';
  2157. }
  2158. $levelInfo = $systemUserLevelServices->getWhereLevelList([], 'id,name');
  2159. $groupInfo = $userGroupServices->getGroupList();
  2160. $labelInfo = $userLabelCateServices->getUserLabel($uid);
  2161. return compact('userInfo', 'levelInfo', 'groupInfo', 'labelInfo');
  2162. }
  2163. /**
  2164. * 新用户注册奖励
  2165. * @param int $id
  2166. * @return bool
  2167. * @throws Exception
  2168. *
  2169. * @date 2022/09/28
  2170. * @author yyw
  2171. */
  2172. public function rewardNewUser(int $id)
  2173. {
  2174. $user = $this->getUserInfo($id);
  2175. if (!$user) {
  2176. throw new AdminException(100026);
  2177. }
  2178. $res1 = false;
  2179. $res2 = false;
  2180. $reward_money = sys_config('reward_money');
  2181. $reward_integral = sys_config('reward_integral');
  2182. $edit = array();
  2183. if ($reward_money > 0) {//余额增加
  2184. /** @var UserMoneyServices $userMoneyServices */
  2185. $userMoneyServices = app()->make(UserMoneyServices::class);
  2186. $edit['now_money'] = bcadd($user['now_money'], $reward_money, 2);
  2187. $res1 = $userMoneyServices->income('register_system_add', $user['uid'], $reward_money, $edit['now_money'], 1);
  2188. } else {
  2189. $res1 = true;
  2190. }
  2191. if ($reward_integral > 0) {//积分增加
  2192. /** @var UserBillServices $userBill */
  2193. $userBill = app()->make(UserBillServices::class);
  2194. $integral_data = ['link_id' => 1, 'number' => $reward_integral];
  2195. $edit['integral'] = bcadd($user['integral'], $reward_integral, 2);
  2196. $integral_data['balance'] = $edit['integral'];
  2197. $integral_data['title'] = '新用户注册增加积分';
  2198. $integral_data['mark'] = '新用户注册增加了' . floatval($reward_integral) . '积分';
  2199. $res2 = $userBill->incomeIntegral($user['uid'], 'system_add', $integral_data);
  2200. } else {
  2201. $res2 = true;
  2202. }
  2203. if ($edit) {
  2204. $res3 = $this->dao->update($id, $edit);
  2205. } else {
  2206. $res3 = true;
  2207. }
  2208. if ($res1 && $res2 && $res3) {
  2209. return true;
  2210. } else {
  2211. throw new AdminException(100007);
  2212. }
  2213. }
  2214. /**
  2215. * 推送用户信息
  2216. * @param $data
  2217. * @param $pushUrl
  2218. * @return bool
  2219. */
  2220. public function userUpdate($data, $pushUrl)
  2221. {
  2222. return out_push($pushUrl, $data, '更新用户信息');
  2223. }
  2224. }