User.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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 $payMoney, int $scene = AccumulatePointsScene::RECHARGE, string $describe = '')
  285. {
  286. $rate = SettingModel::getItem('points_rate')['points_2_money'];
  287. $points = bcmul(strval($payMoney),$rate,0);
  288. // 新增积分变动明细
  289. AccumulatePointsLog::add([
  290. 'user_id' => $userId,
  291. 'value' => $points,
  292. 'scene' => $scene,
  293. 'describe' => $describe,
  294. ]);
  295. // 更新用户可用积分
  296. return (new static)->setDec($userId, 'accumulate_points', intval($points));
  297. }
  298. /**
  299. * 多字段增减
  300. * @param array|int|bool $where 支持自增ID 也支持where语句
  301. * @param array $incData //自增字段
  302. * @param array $decData //自减字段
  303. * @param array $data //正常update字段
  304. * @return mixed
  305. */
  306. public static function setIncDecByField($where, $incData , $decData, $data=[])
  307. {
  308. return (new static)->setIncDec($where, $incData, $decData, $data);
  309. }
  310. /**
  311. * 字段递减
  312. * @param array|int|bool $where 支持自增ID 也支持where语句
  313. * @param string $field //字段
  314. * @param float $step //
  315. * @param array $data //正常update字段
  316. * @return mixed
  317. */
  318. public static function setDecByField($where, string $field, float $step = 1)
  319. {
  320. return (new static)->setDec($where, $field, $step);
  321. }
  322. /**
  323. * 字段递增
  324. * @param array|int|bool $where 支持自增ID 也支持where语句
  325. * @param string $field //字段
  326. * @param float $step //
  327. * @param array $data //正常update字段
  328. * @return mixed
  329. */
  330. public static function setIncByField($where, string $field, float $step = 1)
  331. {
  332. return (new static)->setInc($where, $field, $step);
  333. }
  334. /**
  335. * 创建新用户通过手机号,用于管理后台门店管理模块
  336. * 注:该方法只适用于后台门店管理创建新用户
  337. * @param $nickname
  338. * @param $mobile
  339. * @param int $shopsId
  340. * @param int $role
  341. * @return false|mixed
  342. * @throws \think\db\exception\DataNotFoundException
  343. * @throws \think\db\exception\DbException
  344. * @throws \think\db\exception\ModelNotFoundException
  345. */
  346. public static function createUserByMobile($nickname,$mobile,$shopsId=0, int $role=self::NORMAL_USER,$bindShopId = \app\store\model\Shops::ZD_SHOP_ID){
  347. Log::error(__METHOD__.',role ---:'.$role);
  348. $oldUser = User::where('mobile', $mobile)->find();
  349. if ($oldUser && !$oldUser->isEmpty()){
  350. $userId = $oldUser->getAttr('user_id');
  351. // 要清空上级关系
  352. $up = [
  353. 'upper_user_id' => 0,
  354. 'bind_shop_id' => 0
  355. ];
  356. if ($oldUser->getAttr('role') != $role){
  357. $up['role'] = $role;
  358. $up['shop_id'] = $shopsId;
  359. }
  360. User::where('user_id',$userId)->update($up);
  361. return $userId;
  362. }
  363. //上级用户id,店铺id,角色身份
  364. $user = new self();
  365. //$data = ['nick_name'=>$nickname,'mobile'=>$mobile,'shop_id'=>$shopsId,'role'=>$role,"store"=>getStoreId()];
  366. try {
  367. //需要在名厨数据库加用户
  368. $postData = [
  369. 'mobile' => $mobile,
  370. 'openid' => "",
  371. 'source' => 12
  372. ];
  373. $res = curl_post(config('chef.serv_cookhome').'/api/wx/third_platform_register', $postData);
  374. if ($res == false){
  375. Log::error($mobile.'系统繁忙');
  376. return false;
  377. }
  378. $res = json_decode($res, true);
  379. // 获取名厨用户id
  380. if (!isset($res['id']) || !$res['id']){
  381. Log::error($mobile.'系统繁忙');
  382. return false;
  383. }
  384. $chef_user_id = $res['id'];
  385. Log::error(__METHOD__.',role ---:'.$role);
  386. $user->user_id = $chef_user_id;
  387. $user->nick_name = $nickname;
  388. $user->mobile = $mobile;
  389. $user->shop_id = $shopsId;
  390. $user->bind_shop_id = 0;
  391. $user->role = $role;
  392. $user->store = getStoreId();
  393. $user->save();
  394. }catch (\Exception $e){
  395. Log::error($e->getMessage());
  396. return false;
  397. }
  398. return $user->user_id;
  399. }
  400. /**
  401. * @param $shopId
  402. * @param $roles
  403. * @return array
  404. * @throws \think\db\exception\DataNotFoundException
  405. * @throws \think\db\exception\DbException
  406. * @throws \think\db\exception\ModelNotFoundException
  407. */
  408. public static function getCommissionUsers($shopId,$roles): array
  409. {
  410. return self::where('shop_id',$shopId)->whereIn('role',$roles)->field('user_id,role')->select()->toArray();
  411. }
  412. /**
  413. * 店员交接
  414. * @param $userId
  415. * @param $role
  416. * @return bool
  417. */
  418. public function updateUserRole($userId,$role=self::NORMAL_USER){
  419. User::where('user_id',$userId)->update(['role'=>$role,'shop_id'=>0]);
  420. return true;
  421. }
  422. /**
  423. * 交接顾客
  424. * @param $userId
  425. * @param $toUserId
  426. * @param $shopId
  427. * @return bool
  428. */
  429. public function consumersHandover($userId,$toUserId,$shopId){
  430. $count = User::where('upper_user_id',$userId)->where('bind_shop_id',$shopId)->count();
  431. User::where('upper_user_id',$userId)->where('bind_shop_id',$shopId)->update(['upper_user_id'=>$toUserId]);
  432. return $count;
  433. }
  434. /**
  435. * 生成虚拟手机号
  436. * @return string
  437. */
  438. public static function makeVirtualMobile($type)
  439. {
  440. $last = Shops::where('is_virtual', Shops::SHOP_TYPE_VIRTUAL)->count();
  441. $prefix = "YSCV";
  442. // $mobile = $prefix.time().rand(100, 999);
  443. $mobile = $prefix."166".str_pad((string)($last+1),7,"0",STR_PAD_LEFT).$type;
  444. // 检查是否存在
  445. if (User::where('mobile', $mobile)->count() > 0) {
  446. return false;
  447. }
  448. return $mobile;
  449. }
  450. /**
  451. * 生成虚拟名字
  452. * @return string
  453. */
  454. public static function makeVirtualName($prefix = '')
  455. {
  456. $last = Shops::where('is_virtual', Shops::SHOP_TYPE_VIRTUAL)->count();
  457. $name = $prefix.str_pad((string)($last+1),2,"0",STR_PAD_LEFT);
  458. return $name;
  459. }
  460. /**
  461. *获取未下过单的用户ID
  462. */
  463. public static function getNewUserIds(){
  464. $lists = self::alias('us')->where('is_delete',0)
  465. ->whereNotExists('select 1 from yoshop_order where user_id=us.user_id and pay_status=20')
  466. ->field('us.user_id')->select();
  467. return $lists->column('user_id');
  468. }
  469. /**
  470. *获取下过单的用户ID
  471. */
  472. public static function getOldUserIds(){
  473. $lists = self::alias('us')->where('is_delete',0)
  474. ->whereExists('select 1 from yoshop_order where user_id=us.user_id and pay_status=20')
  475. ->field('us.user_id')->select();
  476. return $lists->column('user_id');
  477. }
  478. }