zhangdehua 1 год назад
Родитель
Сommit
1ab90f1fc9

+ 7 - 7
app/index/controller/Cart.php

@@ -8,13 +8,12 @@
 // +----------------------------------------------------------------------
 // | Author: 萤火科技 <admin@yiovo.com>
 // +----------------------------------------------------------------------
-declare (strict_types = 1);
+declare (strict_types=1);
 
 namespace app\index\controller;
 
-use app\api\controller\Controller;
 use app\api\model\Cart as CartModel;
-use app\api\service\Cart as CartService;
+use app\index\service\Cart as CartService;
 use app\common\exception\BaseException;
 use think\facade\Session;
 use think\response\Json;
@@ -32,9 +31,10 @@ class Cart extends Controller
      */
     public function shoppingCart()
     {
-        $accessToken = Session::get('access_token');
-        $userId = Session::get('user_id');
-        //dd($userId,$accessToken);
+//        $userId = Session::get('user_id');
+//        if (empty($userId)){
+//            return view('passport/login');
+//        }
 
         // 购物车商品列表
         $service = new CartService;
@@ -42,7 +42,7 @@ class Cart extends Controller
         // 购物车商品总数量
         $cartTotal = (new CartModel)->getCartTotal();
 
-        return view('shoppingCart');
+        return view('shoppingCart', ['list' => $list, 'cartTotal' => $cartTotal]);
     }
 
     /**

+ 11 - 4
app/index/controller/Controller.php

@@ -13,11 +13,12 @@ declare (strict_types=1);
 namespace app\index\controller;
 
 use think\facade\Log;
+use think\facade\Session;
 use think\response\Json;
 use cores\BaseController;
 use app\api\model\User as UserModel;
 use app\api\model\Store as StoreModel;
-use app\api\service\User as UserService;
+use app\index\service\User as UserService;
 use cores\exception\BaseException;
 
 /**
@@ -42,6 +43,13 @@ class Controller extends BaseController
         $this->checkStore();
         // 验证当前客户端状态
         $this->checkClient();
+        $contrName =  $this->request->controller();
+       if (strtolower($contrName) == 'cart'){
+           $userId = Session::get('user_id');
+           if (empty($userId)){
+               return view('passport/login');
+           }
+       }
     }
 
     /**
@@ -92,13 +100,12 @@ class Controller extends BaseController
 
     /**
      * 获取当前用户信息
-     * @param bool $isForce 强制验证登录
      * @return UserModel|bool|null
      * @throws BaseException
      */
-    protected function getLoginUser(bool $isForce = true)
+    protected function getLoginUserId()
     {
-        return UserService::getCurrentLoginUser($isForce);
+        return UserService::getCurrentLoginUserId();
     }
 
     /**

+ 106 - 0
app/index/model/User.php

@@ -0,0 +1,106 @@
+<?php
+// +----------------------------------------------------------------------
+// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
+// +----------------------------------------------------------------------
+// | Copyright (c) 2017~2021 https://www.yiovo.com All rights reserved.
+// +----------------------------------------------------------------------
+// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
+// +----------------------------------------------------------------------
+// | Author: 萤火科技 <admin@yiovo.com>
+// +----------------------------------------------------------------------
+declare (strict_types=1);
+
+namespace app\index\model;
+
+use think\facade\Cache;
+use app\api\service\User as UserService;
+use app\api\model\UserOauth as UserOauthModel;
+use app\common\model\User as UserModel;
+use cores\exception\BaseException;
+use yiovo\captcha\facade\CaptchaApi;
+
+/**
+ * 用户模型类
+ * Class User
+ * @package app\api\model
+ */
+class User extends UserModel
+{
+    /**
+     * 隐藏字段
+     * @var array
+     */
+    protected $hidden = [
+        'open_id',
+        'is_delete',
+        'store_id',
+        'create_time',
+        'update_time'
+    ];
+
+    /**
+     * 获取器:隐藏手机号中间四位
+     * @param string $value
+     * @return string
+     */
+    public function getMobileAttr(string $value): string
+    {
+        return strlen($value) === 11 ? hide_mobile($value) : $value;
+    }
+
+    /**
+     * 获取用户信息
+     * @param int $userId
+     * @return User|array|false|null
+     * @throws BaseException
+     */
+    public static function getUserById(int $userId)
+    {
+        // 用户基本信息
+        $userInfo = self::detail($userId);
+        if (empty($userInfo) || $userInfo['is_delete']) {
+            throwError('很抱歉,用户信息不存在或已删除', config('status.not_logged'));
+        }
+        // 获取用户关联的第三方用户信息(当前客户端)
+        try {
+            $userInfo['currentOauth'] = UserOauthModel::getOauth($userId, getPlatform());
+        } catch (\Throwable $e) {
+            throwError($e->getMessage());
+        }
+        return $userInfo;
+    }
+
+    /**
+     * 绑定手机号(当前登录用户)
+     * @param array $data
+     * @return bool
+     * @throws BaseException
+     */
+    public function bindMobile(array $data): bool
+    {
+        // 当前登录的用户信息
+        $userInfo = UserService::getCurrentLoginUser(true);
+        // 验证绑定的手机号
+        $this->checkBindMobile($data);
+        // 更新手机号记录
+        return $userInfo->save(['mobile' => $data['mobile']]);
+    }
+
+    /**
+     * 验证绑定的手机号
+     * @param array $data
+     * @return void
+     * @throws BaseException
+     */
+    private function checkBindMobile(array $data): void
+    {
+        // 验证短信验证码是否匹配
+        if (!CaptchaApi::checkSms($data['smsCode'], $data['mobile'])) {
+            throwError('短信验证码不正确');
+        }
+        // 判断手机号是否已存在
+        if (static::checkExistByMobile($data['mobile'])) {
+            throwError('很抱歉,该手机号已绑定其他账户');
+        }
+    }
+}

+ 167 - 0
app/index/service/Cart.php

@@ -0,0 +1,167 @@
+<?php
+// +----------------------------------------------------------------------
+// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
+// +----------------------------------------------------------------------
+// | Copyright (c) 2017~2021 https://www.yiovo.com All rights reserved.
+// +----------------------------------------------------------------------
+// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
+// +----------------------------------------------------------------------
+// | Author: 萤火科技 <admin@yiovo.com>
+// +----------------------------------------------------------------------
+declare (strict_types=1);
+
+namespace app\index\service;
+
+use app\api\model\Cart as CartModel;
+use app\api\model\Goods as GoodsModel;
+use app\index\service\User as UserService;
+use cores\exception\BaseException;
+use app\common\library\helper;
+use app\common\service\BaseService;
+
+/**
+ * 服务类: 购物车
+ * Class Cart
+ * @package app\api\service
+ */
+class Cart extends BaseService
+{
+    /**
+     * 购物车商品列表(用于购物车页面)
+     * @param array $cartIds 购物车记录ID集
+     * @param bool $isGoodsGradeMoney 是否设置商品会员价
+     * @return array|\think\Collection
+     * @throws BaseException
+     * @throws \think\db\exception\DataNotFoundException
+     * @throws \think\db\exception\DbException
+     * @throws \think\db\exception\ModelNotFoundException
+     */
+    public function getList(array $cartIds = [], bool $isGoodsGradeMoney = true)
+    {
+        // 购物车列表
+        $cartList = $this->getCartList($cartIds);
+        if ($cartList->isEmpty()){
+            return [];
+        }
+        // 整理商品ID集
+        $goodsIds = helper::getArrayColumn($cartList, 'goods_id');
+        if (empty($goodsIds)) return [];
+        // 获取商品列表
+        $goodsList = $this->getGoodsListByIds($goodsIds, $isGoodsGradeMoney);
+        // 整理购物车商品列表
+        foreach ($cartList as $cartIdx => $item) {
+            // 查找商品, 商品不存在则删除该购物车记录
+            $result = $this->findGoods($goodsList, $item, $isGoodsGradeMoney);
+            if ($result !== false) {
+                $cartList[$cartIdx]['goods'] = $result;
+            } else {
+                $this->clear([$item['id']]);
+                unset($cartList[$cartIdx]);
+            }
+        }
+        return $cartList;
+    }
+
+    /**
+     * 获取购物车商品列表(用于订单结算台)
+     * @param array $cartIds 购物车记录ID集
+     * @return array
+     * @throws BaseException
+     * @throws \think\db\exception\DataNotFoundException
+     * @throws \think\db\exception\DbException
+     * @throws \think\db\exception\ModelNotFoundException
+     */
+    public function getOrderGoodsList(array $cartIds = []): array
+    {
+        // 购物车列表
+        $cartList = $this->getList($cartIds, false);
+        // 订单商品列表
+        $goodsList = [];
+        foreach ($cartList as $item) {
+            // 商品记录
+            $goods = $item['goods'];
+            // 商品单价
+            $goods['goods_price'] = $goods['skuInfo']['goods_price'];
+            // 商品购买数量
+            $goods['total_num'] = $item['goods_num'];
+            // 商品SKU索引
+            $goods['goods_sku_id'] = $item['goods_sku_id'];
+            // 商品购买总金额
+            $goods['total_price'] = helper::bcmul($goods['goods_price'], $item['goods_num']);
+            $goodsList[] = $goods;
+        }
+        return $goodsList;
+    }
+
+    /**
+     * 检索查询商品
+     * @param mixed $goodsList 商品列表
+     * @param CartModel $item 购物车记录
+     * @param bool $isGoodsGradeMoney 是否设置商品会员价
+     * @return false|mixed
+     * @throws BaseException
+     */
+    private function findGoods($goodsList, CartModel $item, bool $isGoodsGradeMoney = true)
+    {
+        // 查找商品记录
+        $goodsInfo = helper::getArrayItemByColumn($goodsList, 'goods_id', $item['goods_id']);
+        if (empty($goodsInfo)) {
+            return false;
+        }
+        // 获取当前选择的商品SKU信息
+        $goodsInfo['skuInfo'] = GoodsModel::getSkuInfo($goodsInfo, $item['goods_sku_id'], $isGoodsGradeMoney);
+        // 这里需要用到clone, 因对象是引用传递 后面的值会覆盖前面的
+        return clone $goodsInfo;
+    }
+
+    /**
+     * 删除购物车中指定记录
+     * @param array $cartIds
+     * @return bool
+     * @throws BaseException
+     */
+    public function clear(array $cartIds = []): bool
+    {
+        $model = new CartModel;
+        return $model->clear($cartIds);
+    }
+
+    /**
+     * 根据商品ID集获取商品列表
+     * @param array $goodsIds
+     * @param bool $isGoodsGradeMoney 是否设置会员折扣价
+     * @return mixed
+     */
+    private function getGoodsListByIds(array $goodsIds, bool $isGoodsGradeMoney = true)
+    {
+        $model = new GoodsModel;
+        return $model->isGoodsGradeMoney($isGoodsGradeMoney)->getListByIdsFromApi($goodsIds);
+    }
+
+    /**
+     * 获取当前用户的购物车记录
+     * @param array $cartIds 购物车记录ID集
+     * @return \think\Collection
+     * @throws BaseException
+     * @throws \think\db\exception\DataNotFoundException
+     * @throws \think\db\exception\DbException
+     * @throws \think\db\exception\ModelNotFoundException
+     */
+    private function getCartList(array $cartIds = []): \think\Collection
+    {
+        // 当前用户ID
+        $userId = UserService::getCurrentLoginUserId();
+        // 购物车记录模型
+        $model = new CartModel;
+        // 检索查询条件
+        $filter = [];
+        if (!empty($cartIds)) {
+            $filter[] = ['id', 'in', $cartIds];
+        }
+        // 查询列表记录
+        return $model->where($filter)
+            ->where('user_id', '=', $userId)
+            ->where('is_delete', '=', 0)
+            ->select();
+    }
+}

+ 8 - 65
app/index/service/User.php

@@ -12,10 +12,12 @@ declare (strict_types = 1);
 
 namespace app\index\service;
 
-use app\api\model\User as UserModel;
+use app\index\model\User as UserModel;
 use app\api\model\UserOauth as UserOauthModel;
 use app\common\service\BaseService;
 use cores\exception\BaseException;
+use think\facade\Session;
+use think\Response;
 
 /**
  * 用户服务类
@@ -25,28 +27,9 @@ use cores\exception\BaseException;
 class User extends BaseService
 {
     // 当前登录的会员信息
-    private static $currentLoginUser;
 
-    /**
-     * 获取当前登录的用户信息 (快捷)
-     * 可在api应用中的任意模块中调用此方法(controller model service)
-     * 已登录情况下返回用户信息, 未登录返回false
-     * @param bool $isForce 是否强制验证登录, 如果未登录将抛错
-     * @return false|UserModel
-     * @throws BaseException
-     */
-    public static function getCurrentLoginUser(bool $isForce = false)
-    {
-        $service = new static;
-        if (empty(static::$currentLoginUser)) {
-            static::$currentLoginUser = $service->getLoginUser();
-            if (empty(static::$currentLoginUser)) {
-                $isForce && throwError($service->getError(), config('status.not_logged'));
-                return false;
-            }
-        }
-        return static::$currentLoginUser;
-    }
+    public const USER_TOKEN = 'access_token';
+    public const USER_ID = 'user_id';
 
     /**
      * 获取当前登录的用户ID
@@ -56,8 +39,7 @@ class User extends BaseService
      */
     public static function getCurrentLoginUserId()
     {
-        $userInfo = static::getCurrentLoginUser(true);
-        return $userInfo['user_id'];
+        return Session::get(self::USER_ID);
     }
 
     /**
@@ -80,48 +62,9 @@ class User extends BaseService
      * @return bool
      * @throws BaseException
      */
-    public static function isLogin(bool $isForce = false)
-    {
-        return !empty(static::getCurrentLoginUser($isForce));
-    }
-
-    /**
-     * 获取当前登录的用户信息
-     * @return UserModel|array|false|null
-     * @throws BaseException
-     */
-    private function getLoginUser()
-    {
-        // 获取用户认证Token
-        if (!$token = $this->getToken()) {
-            return false;
-        }
-        // 获取用户信息
-        if (!$user = UserModel::getUserByToken($token)) {
-            $this->error = '没有找到用户信息';
-            return false;
-        }
-        return $user;
-    }
-
-    /**
-     * 获取用户认证Token
-     * @return bool|string
-     */
-    protected function getToken()
+    public static function isLogin()
     {
-        // 获取请求中的token
-        $token = $this->request->header('Access-Token');
-        // 调试模式下可通过param
-        if (empty($token) && is_debug()) {
-            $token = $this->request->param('Access-Token');
-        }
-        // 不存在token报错
-        if (empty($token)) {
-            $this->error = '缺少必要的参数token, 请先登录';
-            return false;
-        }
-        return $token;
+        return !empty(Session::get(self::USER_TOKEN));
     }
 
 }

+ 10 - 0
app/index/view/error.html

@@ -0,0 +1,10 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+    <title>Title</title>
+</head>
+<body>
+    wocuole
+</body>
+</html>

+ 2 - 4
app/index/view/index/productDetails.html

@@ -367,14 +367,11 @@
                     //注册成功后进入
                     if (obj.status === 200 || obj.status === '200') {
                         showToast("Successful")
+                        window.location.href = '../cart/shoppingCart';
                         return
-
                     }
-
                 }
-
             })
-            console.log("商品数量", number)
         }
 
         /**
@@ -461,6 +458,7 @@
                         //注册成功后进入
                         if (obj.status === 200 || obj.status === '200') {
                             showToast("Successful")
+                            window.location.href = '../cart/shoppingCart';
                             return
 
                         }