User.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2021 https://www.yiovo.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
  8. // +----------------------------------------------------------------------
  9. // | Author: 萤火科技 <admin@yiovo.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace app\common\model;
  13. use app\common\enum\user\AccumulatePointsScene;
  14. use app\common\model\user\AccumulatePointsLog;
  15. use app\common\library\helper;
  16. use app\common\model\store\Setting as SettingModel;
  17. use app\common\model\user\CommissionsDetail;
  18. use app\common\model\user\PointsLog as PointsLogModel;
  19. use app\common\model\user\UserIdcards;
  20. use app\common\service\BaseService;
  21. use think\Exception;
  22. use think\facade\Log;
  23. use think\model\relation\BelongsTo;
  24. use think\model\relation\HasMany;
  25. use think\model\relation\HasOne;
  26. /**
  27. * 用户模型类
  28. * Class User
  29. * @package app\common\model
  30. */
  31. class User extends BaseModel
  32. {
  33. // 定义表名
  34. protected $name = 'user';
  35. // 定义主键
  36. protected $pk = 'user_id';
  37. // 性别
  38. private $gender = [0 => '未知', 1 => '男', 2 => '女'];
  39. // 用户角色
  40. const ROLE_ARR = [1 => '普通用户', 2 => '店老板', 3 => '店长', 4 => '店员', 5 => '厨师',99=>'推荐官'];
  41. const COMMISSION_ARR = [1 => '普通推荐官', 2 => '高级推荐官', 3 => '超级推荐官'];
  42. const NORMAL_USER = 1;
  43. const SHOP_BOSS = 2;
  44. const SHOP_MG = 3;
  45. const SHOP_SELLER = 4;
  46. const SHOP_CHEF = 5;
  47. const COMMISSION_USER = 99;
  48. /*用户活动来源 start*/
  49. const ACT_SOURCE_PROMOTION_MONITOR = 1; // 渠道推广
  50. const ACT_SOURCE_GROUP_BUY = 2;//拼团活动
  51. const ACT_SOURCE_KJ = 3;//砍价活动
  52. const ACT_SOURCE_GROUP_BUY_LB = 4;//拼团裂变活动
  53. /*用户活动来源 end*/
  54. //TODO 有新增活动来源时请补充下面的 ACT_SOURCE_OPTIONS
  55. const ACT_SOURCE_OPTIONS = [0 => '未区分来源', 1 => '渠道推广',2 => '拼团活动', 3 => '砍价活动',4=>'拼团裂变'];
  56. /**
  57. * 关联用户头像表
  58. * @return HasOne
  59. */
  60. public function avatar()
  61. {
  62. return $this->hasOne('uploadFile', 'file_id', 'avatar_id')
  63. ->bind(['avatar_url' => 'preview_url']);
  64. }
  65. /**
  66. * 关联会员等级表
  67. * @return BelongsTo
  68. */
  69. public function grade()
  70. {
  71. $module = self::getCalledModule();
  72. return $this->belongsTo("app\\{$module}\\model\\user\\Grade", 'grade_id');
  73. }
  74. /**
  75. * 关联收货地址表
  76. * @return HasMany
  77. */
  78. public function address()
  79. {
  80. return $this->hasMany('UserAddress');
  81. }
  82. /**
  83. * 关联收货地址表 (默认地址)
  84. * @return BelongsTo
  85. */
  86. public function addressDefault()
  87. {
  88. return $this->belongsTo('UserAddress', 'address_id');
  89. }
  90. public function shops()
  91. {
  92. return $this->hasOne('Shops', 'shop_id', 'shop_id');
  93. }
  94. public function bindShops()
  95. {
  96. return $this->hasOne('Shops', 'shop_id', 'bind_shop_id');
  97. }
  98. public function upperUser()
  99. {
  100. return $this->hasOne('User', 'user_id', 'upper_user_id');
  101. }
  102. public function idcard()
  103. {
  104. return $this->hasOne(UserIdcards::class, 'user_id', 'user_id');
  105. }
  106. /**
  107. * 获取器:显示性别
  108. * @param $value
  109. * @return mixed
  110. */
  111. public function getGenderAttr($value)
  112. {
  113. return $this->gender[$value];
  114. }
  115. public function getRoleTextAttr($value, $data)
  116. {
  117. $role = $data['role']??1;
  118. if ($role == self::COMMISSION_USER){
  119. return self::COMMISSION_ARR[$data['seller_grade']??1];
  120. }
  121. return self::ROLE_ARR[$role] ?? '';
  122. }
  123. public function getWjsyjAmountAttr(){
  124. $sum_fc_amount = CommissionsDetail::where("user_id",$this->user_id)->where("clearing_status",0)->sum('clearing_money');
  125. return $sum_fc_amount;
  126. }
  127. public function getLastLoginTimeAttr($value)
  128. {
  129. return $value ? date('Y-m-d H:i:s') : '';
  130. }
  131. /**
  132. * 获取用户信息
  133. * @param $where
  134. * @param array $with
  135. * @return array|null|static
  136. */
  137. public static function detail($where, $with = [])
  138. {
  139. $filter = ['is_delete' => 0];
  140. if (is_array($where)) {
  141. $filter = array_merge($filter, $where);
  142. } else {
  143. $filter['user_id'] = (int)$where;
  144. }
  145. return static::get($filter, $with);
  146. }
  147. /**
  148. * 累积用户的实际消费金额
  149. * @param int $userId
  150. * @param $expendMoney
  151. * @return mixed
  152. */
  153. public static function setIncUserExpend(int $userId, float $expendMoney)
  154. {
  155. return (new static)->setInc($userId, 'expend_money', $expendMoney);
  156. }
  157. /**
  158. * 累积用户可用余额
  159. * @param int $userId
  160. * @param $money
  161. * @return mixed
  162. */
  163. public static function setIncBalance(int $userId, float $money)
  164. {
  165. return (new static)->setInc($userId, 'balance', $money);
  166. }
  167. /**
  168. * 消减用户可用余额
  169. * @param int $userId
  170. * @param $money
  171. * @return mixed
  172. */
  173. public static function setDecBalance(int $userId, float $money)
  174. {
  175. return (new static)->setDec([['user_id', '=', $userId]], 'balance', $money);
  176. }
  177. /**
  178. * 指定会员等级下是否存在用户
  179. * @param int $gradeId
  180. * @return bool
  181. */
  182. public static function checkExistByGradeId(int $gradeId)
  183. {
  184. $model = new static;
  185. return (bool)$model->where('grade_id', '=', (int)$gradeId)
  186. ->where('is_delete', '=', 0)
  187. ->value('user_id');
  188. }
  189. /**
  190. * 累积用户总消费金额
  191. * @param int $userId
  192. * @param $money
  193. * @return mixed
  194. */
  195. public static function setIncPayMoney(int $userId, float $money)
  196. {
  197. return (new static)->setInc($userId, 'pay_money', $money);
  198. }
  199. /**
  200. * 累积用户实际消费的金额 (批量)
  201. * @param array $data
  202. * @return bool
  203. */
  204. public function onBatchIncExpendMoney(array $data)
  205. {
  206. foreach ($data as $userId => $expendMoney) {
  207. static::setIncUserExpend($userId, (float)$expendMoney);
  208. }
  209. return true;
  210. }
  211. /**
  212. * 累积用户的可用积分数量 (批量)
  213. * @param array $data
  214. * @return bool
  215. */
  216. public function onBatchIncPoints(array $data)
  217. {
  218. foreach ($data as $userId => $value) {
  219. $this->setInc($userId, 'points', $value);
  220. }
  221. return true;
  222. }
  223. public static function setIncGrowthValue($user,$money){
  224. if($user['member_expire_time']>time()){ //有会员并且未过期
  225. //用户直接添加用户积分
  226. $growth_value = SettingModel::getItem('member_growth')['growth_value'];
  227. $num = helper::bcmul($money,$growth_value);
  228. return (new static)->setInc($user['user_id'], 'growth_value', (float)$num);
  229. }
  230. }
  231. /**
  232. * 累积用户的可用积分
  233. * @param int $userId 用户ID
  234. * @param int $points 累计的积分
  235. * @param string $describe
  236. * @return mixed
  237. */
  238. public static function setIncPoints(int $userId, int $points, string $describe)
  239. {
  240. // 新增积分变动明细
  241. PointsLogModel::add([
  242. 'user_id' => $userId,
  243. 'value' => $points,
  244. 'describe' => $describe,
  245. ]);
  246. // 更新用户可用积分
  247. return (new static)->setInc($userId, 'points', $points);
  248. }
  249. /**
  250. * @param int $userId
  251. * @param int $payMoney 支付金额
  252. * @param int $scene 积分场景
  253. * @param string $describe
  254. * @return mixed
  255. * @throws \think\db\exception\DataNotFoundException
  256. * @throws \think\db\exception\DbException
  257. * @throws \think\db\exception\ModelNotFoundException
  258. */
  259. public static function setIncAccumulatePoints(int $userId, string $payMoney, int $scene = AccumulatePointsScene::RECHARGE, string $describe = '')
  260. {
  261. $rate = SettingModel::getItem('points_rate')['points_rate'];
  262. $points = bcmul(strval($payMoney),$rate,0);
  263. // 新增积分变动明细
  264. AccumulatePointsLog::add([
  265. 'user_id' => $userId,
  266. 'value' => $points,
  267. 'scene' => $scene,
  268. 'describe' => $describe,
  269. ]);
  270. // 更新用户可用积分
  271. return (new static)->setInc($userId, 'accumulate_points', intval($points));
  272. }
  273. /**
  274. * 积分扣减
  275. * @param int $userId
  276. * @param float $payMoney
  277. * @param int $scene
  278. * @param string $describe
  279. * @return mixed
  280. * @throws \think\db\exception\DataNotFoundException
  281. * @throws \think\db\exception\DbException
  282. * @throws \think\db\exception\ModelNotFoundException
  283. */
  284. public static function setDecAccumulatePoints(int $userId, string $points, int $scene = AccumulatePointsScene::RECHARGE, string $describe = '')
  285. {
  286. // 新增积分变动明细
  287. AccumulatePointsLog::add([
  288. 'user_id' => $userId,
  289. 'value' => $points,
  290. 'scene' => $scene,
  291. 'describe' => $describe,
  292. ]);
  293. // 更新用户可用积分
  294. return (new static)->setDec($userId, 'accumulate_points', intval($points));
  295. }
  296. /**
  297. * 多字段增减
  298. * @param array|int|bool $where 支持自增ID 也支持where语句
  299. * @param array $incData //自增字段
  300. * @param array $decData //自减字段
  301. * @param array $data //正常update字段
  302. * @return mixed
  303. */
  304. public static function setIncDecByField($where, $incData , $decData, $data=[])
  305. {
  306. return (new static)->setIncDec($where, $incData, $decData, $data);
  307. }
  308. /**
  309. * 字段递减
  310. * @param array|int|bool $where 支持自增ID 也支持where语句
  311. * @param string $field //字段
  312. * @param float $step //
  313. * @param array $data //正常update字段
  314. * @return mixed
  315. */
  316. public static function setDecByField($where, string $field, float $step = 1)
  317. {
  318. return (new static)->setDec($where, $field, $step);
  319. }
  320. /**
  321. * 字段递增
  322. * @param array|int|bool $where 支持自增ID 也支持where语句
  323. * @param string $field //字段
  324. * @param float $step //
  325. * @param array $data //正常update字段
  326. * @return mixed
  327. */
  328. public static function setIncByField($where, string $field, float $step = 1)
  329. {
  330. return (new static)->setInc($where, $field, $step);
  331. }
  332. /**
  333. * 创建新用户通过手机号,用于管理后台门店管理模块
  334. * 注:该方法只适用于后台门店管理创建新用户
  335. * @param $nickname
  336. * @param $mobile
  337. * @param int $shopsId
  338. * @param int $role
  339. * @return false|mixed
  340. * @throws \think\db\exception\DataNotFoundException
  341. * @throws \think\db\exception\DbException
  342. * @throws \think\db\exception\ModelNotFoundException
  343. */
  344. public static function createUserByMobile($nickname,$mobile,$shopsId=0, int $role=self::NORMAL_USER,$bindShopId = \app\store\model\Shops::ZD_SHOP_ID){
  345. Log::error(__METHOD__.',role ---:'.$role);
  346. $oldUser = User::where('mobile', $mobile)->find();
  347. if ($oldUser && !$oldUser->isEmpty()){
  348. $userId = $oldUser->getAttr('user_id');
  349. // 要清空上级关系
  350. $up = [
  351. 'upper_user_id' => 0,
  352. 'bind_shop_id' => 0
  353. ];
  354. if ($oldUser->getAttr('role') != $role){
  355. $up['role'] = $role;
  356. $up['shop_id'] = $shopsId;
  357. }
  358. User::where('user_id',$userId)->update($up);
  359. return $userId;
  360. }
  361. //上级用户id,店铺id,角色身份
  362. $user = new self();
  363. //$data = ['nick_name'=>$nickname,'mobile'=>$mobile,'shop_id'=>$shopsId,'role'=>$role,"store"=>getStoreId()];
  364. try {
  365. //需要在名厨数据库加用户
  366. // $postData = [
  367. // 'mobile' => $mobile,
  368. // 'openid' => "",
  369. // 'source' => 12
  370. // ];
  371. // $res = curl_post(config('chef.serv_cookhome').'/api/wx/third_platform_register', $postData);
  372. // if ($res == false){
  373. // Log::error($mobile.'系统繁忙');
  374. // return false;
  375. // }
  376. // $res = json_decode($res, true);
  377. // // 获取名厨用户id
  378. // if (!isset($res['id']) || !$res['id']){
  379. // Log::error($mobile.'系统繁忙');
  380. // return false;
  381. // }
  382. //$chef_user_id = $res['id'];
  383. Log::error(__METHOD__.',role ---:'.$role);
  384. //$user->user_id = $chef_user_id;
  385. $user->nick_name = $nickname;
  386. $user->mobile = $mobile;
  387. $user->shop_id = $shopsId;
  388. $user->bind_shop_id = 0;
  389. $user->role = $role;
  390. $user->store = getStoreId();
  391. $user->save();
  392. }catch (\Exception $e){
  393. Log::error($e->getMessage());
  394. return false;
  395. }
  396. return $user->user_id;
  397. }
  398. /**
  399. * @param $shopId
  400. * @param $roles
  401. * @return array
  402. * @throws \think\db\exception\DataNotFoundException
  403. * @throws \think\db\exception\DbException
  404. * @throws \think\db\exception\ModelNotFoundException
  405. */
  406. public static function getCommissionUsers($shopId,$roles): array
  407. {
  408. return self::where('shop_id',$shopId)->whereIn('role',$roles)->field('user_id,role')->select()->toArray();
  409. }
  410. /**
  411. * 店员交接
  412. * @param $userId
  413. * @param $role
  414. * @return bool
  415. */
  416. public function updateUserRole($userId,$role=self::NORMAL_USER){
  417. User::where('user_id',$userId)->update(['role'=>$role,'shop_id'=>0]);
  418. return true;
  419. }
  420. /**
  421. * 交接顾客
  422. * @param $userId
  423. * @param $toUserId
  424. * @param $shopId
  425. * @return bool
  426. */
  427. public function consumersHandover($userId,$toUserId,$shopId){
  428. $count = User::where('upper_user_id',$userId)->where('bind_shop_id',$shopId)->count();
  429. User::where('upper_user_id',$userId)->where('bind_shop_id',$shopId)->update(['upper_user_id'=>$toUserId]);
  430. return $count;
  431. }
  432. /**
  433. * 生成虚拟手机号
  434. * @return string
  435. */
  436. public static function makeVirtualMobile($type)
  437. {
  438. $last = Shops::where('is_virtual', Shops::SHOP_TYPE_VIRTUAL)->count();
  439. $prefix = "YSCV";
  440. // $mobile = $prefix.time().rand(100, 999);
  441. $mobile = $prefix."166".str_pad((string)($last+1),7,"0",STR_PAD_LEFT).$type;
  442. // 检查是否存在
  443. if (User::where('mobile', $mobile)->count() > 0) {
  444. return false;
  445. }
  446. return $mobile;
  447. }
  448. /**
  449. * 生成虚拟名字
  450. * @return string
  451. */
  452. public static function makeVirtualName($prefix = '')
  453. {
  454. $last = Shops::where('is_virtual', Shops::SHOP_TYPE_VIRTUAL)->count();
  455. $name = $prefix.str_pad((string)($last+1),2,"0",STR_PAD_LEFT);
  456. return $name;
  457. }
  458. /**
  459. *获取未下过单的用户ID
  460. */
  461. public static function getNewUserIds(){
  462. $lists = self::alias('us')->where('is_delete',0)
  463. ->whereNotExists('select 1 from yoshop_order where user_id=us.user_id and pay_status=20')
  464. ->field('us.user_id')->select();
  465. return $lists->column('user_id');
  466. }
  467. /**
  468. *获取下过单的用户ID
  469. */
  470. public static function getOldUserIds(){
  471. $lists = self::alias('us')->where('is_delete',0)
  472. ->whereExists('select 1 from yoshop_order where user_id=us.user_id and pay_status=20')
  473. ->field('us.user_id')->select();
  474. return $lists->column('user_id');
  475. }
  476. public static function getByUserIds($userIds = []){
  477. return self::whereIn('user_id',$userIds)->field('user_id,open_id')->select()->toArray();
  478. }
  479. }