Cart.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: zhengmingwei
  5. * Date: 2019/10/27
  6. * Time: 5:37 下午
  7. */
  8. namespace addons\unishop\controller;
  9. use addons\unishop\extend\Hashids;
  10. use addons\unishop\model\Config;
  11. use addons\unishop\model\Product;
  12. use addons\unishop\model\Cart as CartModel;
  13. use think\Exception;
  14. /**
  15. * 购物车
  16. */
  17. class Cart extends Base
  18. {
  19. /**
  20. * 允许频繁访问的接口
  21. * @var array
  22. */
  23. protected $frequently = ['number_change','index', 'choose_change'];
  24. /**
  25. * @ApiTitle (列表)
  26. * @ApiSummary (购物车列表)
  27. * @ApiMethod (GET)
  28. * @ApiHeaders (name=token, type=string, required=true, description="用户登录的Token", sample="a2e3cc70-d2d1-41e6-9c14-f1d774ee5e1e")
  29. * @ApiHeaders (name=cookie, type=string, required=false, description="用户会话的cookie")
  30. * @ApiReturn ({"code":1,"msg":"","data":[]})
  31. *
  32. * @ApiReturnParams (name="market_price", type="string", description="市场价")
  33. * @ApiReturnParams (name="sales_price", type="string", description="销售价")
  34. * @ApiReturnParams (name="stock", type="integer", description="库存")
  35. * @ApiReturnParams (name="sales", type="integer", description="销量")
  36. * @ApiReturnParams (name="image", type="string", description="图片")
  37. * @ApiReturnParams (name="title", type="string", description="商品名称")
  38. * @ApiReturnParams (name="choose", type="integer", description="是否选中")
  39. * @ApiReturnParams (name="isset", type="integer", description="是否生效")
  40. * @ApiReturnParams (name="cart_id", type="integer", description="购物车id")
  41. * @ApiReturnParams (name="spec", type="string", description="选中的规格")
  42. * @ApiReturnParams (name="number", type="integer", description="数量")
  43. * @ApiReturnParams (name="oldPrice", type="string", description="旧价格")
  44. * @ApiReturnParams (name="nowPrice", type="string", description="现价格")
  45. * @ApiReturnParams (name="product_id", type="string", description="商品id")
  46. *
  47. */
  48. public function index()
  49. {
  50. $carts = (new CartModel)->where(['user_id' => $this->auth->id])
  51. ->with([
  52. 'product' => function ($query) {
  53. $query->field(['id', 'image', 'title', 'specTableList','sales','real_sales','market_price','sales_price','stock','use_spec', 'switch']);
  54. }
  55. ])
  56. ->order(['createtime' => 'desc'])
  57. ->select();
  58. if (!$carts) {
  59. // $this->success('', []);
  60. $result = [
  61. 'choose_price_total' => '0',
  62. 'choose_number' => 0,
  63. 'list' => [],
  64. ];
  65. $this->success('', $result);
  66. }
  67. $data = [];
  68. $productExtend = new \addons\unishop\extend\Product;
  69. $choose_price_total = '0';//已选中的总价格
  70. $choose_number = 0;//已选中的个数
  71. foreach ($carts as $item) {
  72. // $oldProduct = json_decode($item['snapshot'], true);
  73. // $oldData = $productExtend->getBaseData($oldProduct, $item['spec'] ?? '');
  74. if (empty($item['product'])) { //商品被删了的情况
  75. continue;//不要了
  76. /*$tempData = $oldData;
  77. $tempData['isset'] = false; // 失效
  78. $tempData['title'] = $oldProduct['title'];
  79. $tempData['choose'] = 0;*/
  80. } else {
  81. $productData = $item['product']->getData();
  82. $tempData = $productExtend->getBaseData($productData, $item['spec'] ?? '');
  83. $tempData['title'] = $item['product']['title'];
  84. $tempData['choose'] = $item['choose']; //是否选中
  85. $tempData['isset'] = true;
  86. if ($productData['switch'] == Product::SWITCH_OFF) {
  87. continue;//不要了
  88. $tempData['isset'] = false; // 失效
  89. $tempData['choose'] = 0;
  90. }
  91. }
  92. $tempData['cart_id'] = $item['id'];
  93. $tempData['spec'] = $item['spec'];
  94. $tempData['number'] = $item['number'];
  95. $tempData['image'] = Config::getImagesFullUrl($tempData['image']);
  96. $tempData['oldPrice'] = round($tempData['sales_price'], 2);
  97. $tempData['nowPrice'] = round($tempData['sales_price'], 2);
  98. //新增此商品总价
  99. $tempData['Price_total'] = bcmul($tempData['sales_price'],$tempData['number'],2);
  100. //已选中商品,总价格
  101. if($item['choose'] == 1){
  102. $choose_price_total = bcadd($choose_price_total,$tempData['Price_total'],2);
  103. $choose_number += $tempData['number'];
  104. }
  105. $tempData['product_id'] = Hashids::encodeHex($item['product_id']);
  106. $data[] = $tempData;
  107. }
  108. $result = [
  109. 'choose_price_total' => $choose_price_total,
  110. 'choose_number' => $choose_number,
  111. 'list' => $data,
  112. ];
  113. $this->success('', $result);
  114. }
  115. /**
  116. * @ApiTitle (添加)
  117. * @ApiSummary (添加商品到购物车)
  118. * @ApiMethod (GET)
  119. * @ApiHeaders (name=token, type=string, required=true, description="用户登录的Token", sample="a2e3cc70-d2d1-41e6-9c14-f1d774ee5e1e")
  120. * @ApiHeaders (name=cookie, type=string, required=false, description="用户会话的cookie")
  121. * @ApiParams (name="id", type="string", description="商品id")
  122. * @ApiReturn ({"code":1,"msg":"添加成功","data":1})
  123. */
  124. public function add()
  125. {
  126. $id = input('id', 0);
  127. $number = input('number',1);
  128. $id = \addons\unishop\extend\Hashids::decodeHex($id);
  129. $product = (new Product)->where(['id' => $id, 'switch' => Product::SWITCH_ON])->find();
  130. if (!$product) {
  131. $this->error('产品不存在或已下架');
  132. }
  133. $spec = input('spec', '');
  134. $productBase = (new \addons\unishop\extend\Product())->getBaseData($product->getData(), $spec);
  135. if (!$productBase['stock'] || $productBase['stock'] <= 0) {
  136. $this->error('库存不足');
  137. }
  138. $user_id = $this->auth->id;
  139. $cartModel = new \addons\unishop\model\Cart();
  140. $cartModel->where(['user_id' => $user_id, 'product_id' => $id]);
  141. $spec && $cartModel->where('spec', $spec);
  142. $oldCart = $cartModel->find();
  143. if ($oldCart) {
  144. //$this->error('商品已存在购物车');
  145. $oldCart->number += $number;
  146. $result = $oldCart->save();
  147. } else {
  148. $cartModel->user_id = $user_id;
  149. $cartModel->product_id = $id;
  150. $spec && $cartModel->spec = $spec;
  151. $cartModel->number = $number;
  152. // $cartModel->snapshot = json_encode($product->getData(), true);
  153. $result = $cartModel->save();
  154. }
  155. if ($result) {
  156. $this->success('添加成功', 1);
  157. } else {
  158. $this->error('添加失败');
  159. }
  160. }
  161. /**
  162. * @ApiTitle (删除)
  163. * @ApiSummary (删除购物车的商品支持多个删除用','号隔开购物车id)
  164. * @ApiMethod (POST)
  165. * @ApiHeaders (name=token, type=string, required=true, description="用户登录的Token", sample="a2e3cc70-d2d1-41e6-9c14-f1d774ee5e1e")
  166. * @ApiHeaders (name=cookie, type=string, required=false, description="用户会话的cookie")
  167. * @ApiParams (name="id", type="string", description="购物车id,多个的话用','号隔开")
  168. * @ApiReturn ({"code":1,"msg":"删除成功","data":1})
  169. */
  170. public function delete()
  171. {
  172. $id = input('id', 0);
  173. $userId = $this->auth->id;
  174. $result = CartModel::destroy(function ($query) use ($id, $userId) {
  175. $query->whereIn('id', $id)->where(['user_id' => $userId]);
  176. });
  177. if ($result) {
  178. $this->success('删除成功', 1);
  179. } else {
  180. $this->error('删除失败', 0);
  181. }
  182. }
  183. /**
  184. * @ApiTitle (修改购物车数量)
  185. * @ApiSummary (修改购物车数量)
  186. * @ApiMethod (GET)
  187. * @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
  188. * @ApiParams (name="id", type=integer, required=true, description="购物车id")
  189. * @ApiParams (name="number", type=integer, required=true, description="数量")
  190. * @ApiReturn ({"code":1,"msg":"更改成功","data":数量})
  191. */
  192. public function number_change()
  193. {
  194. $cart_id = input('id', 0);
  195. $number = input('number', 1);
  196. $cart = CartModel::get(['id' => $cart_id, 'user_id' => $this->auth->id]);
  197. if (empty($cart)) {
  198. $this->error('此商品不存在购物车');
  199. }
  200. $cart->number = $number;
  201. $result = $cart->save();
  202. if ($result) {
  203. $this->success('更改成功', $number);
  204. } else {
  205. $this->error('更改失败', $number);
  206. }
  207. }
  208. /**
  209. * @ApiTitle (修改购物车选中状态)
  210. * @ApiSummary (修改购物车选中状态)
  211. * @ApiMethod (POST)
  212. * @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
  213. * @ApiParams (name="trueArr", type=string, required=true, description="选中的购物车id,多个的话用','号隔开")
  214. * @ApiParams (name="falseArr", type=string, required=true, description="不选的购物车id,多个的话用','号隔开")
  215. * @ApiReturn ({"code":1,"msg":"","data":数量})
  216. */
  217. public function choose_change()
  218. {
  219. $trueArr = input('trueArr', false);
  220. $falseArr = input('falseArr', false);
  221. $user_id = $this->auth->id;
  222. try {
  223. $cart = new CartModel();
  224. if ($trueArr) {
  225. $cart->save(['choose' => CartModel::CHOOSE_ON], function ($query) use ($user_id, $trueArr) {
  226. $query->where('user_id', $user_id)->where('id', 'IN', $trueArr);
  227. });
  228. }
  229. if ($falseArr) {
  230. $cart->save(['choose' => CartModel::CHOOSE_OFF], function ($query) use ($user_id, $falseArr) {
  231. $query->where('user_id', $user_id)->where('id', 'IN', $falseArr);
  232. });
  233. }
  234. } catch (Exception $e) {
  235. $this->error('更新失败', 0);
  236. }
  237. $this->success('', 1);
  238. }
  239. }