Cart.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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', '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','market_price','sales_price','stock','use_spec', 'switch']);
  54. }
  55. ])
  56. ->order(['createtime' => 'desc'])
  57. ->select();
  58. if (!$carts) {
  59. $this->success('', []);
  60. }
  61. $data = [];
  62. $productExtend = new \addons\unishop\extend\Product;
  63. $choose_price_total = 0;//已选中的总价格
  64. $choose_number = 0;//已选中的个数
  65. foreach ($carts as $item) {
  66. $oldProduct = json_decode($item['snapshot'], true);
  67. $oldData = $productExtend->getBaseData($oldProduct, $item['spec'] ?? '');
  68. if (empty($item['product'])) { //商品被删了的情况
  69. continue;//不要了
  70. $tempData = $oldData;
  71. $tempData['isset'] = false; // 失效
  72. $tempData['title'] = $oldProduct['title'];
  73. $tempData['choose'] = 0;
  74. } else {
  75. $productData = $item['product']->getData();
  76. $tempData = $productExtend->getBaseData($productData, $item['spec'] ?? '');
  77. $tempData['title'] = $item['product']['title'];
  78. $tempData['choose'] = $item['choose']; //是否选中
  79. $tempData['isset'] = true;
  80. if ($productData['switch'] == Product::SWITCH_OFF) {
  81. continue;//不要了
  82. $tempData['isset'] = false; // 失效
  83. $tempData['choose'] = 0;
  84. }
  85. }
  86. $tempData['cart_id'] = $item['id'];
  87. $tempData['spec'] = $item['spec'];
  88. $tempData['number'] = $item['number'];
  89. $tempData['image'] = Config::getImagesFullUrl($oldData['image']);
  90. $tempData['oldPrice'] = round($oldData['sales_price'], 2);
  91. $tempData['nowPrice'] = round($tempData['sales_price'], 2);
  92. //新增此商品总价
  93. $tempData['Price_total'] = bcmul($tempData['sales_price'],$tempData['number'],2);
  94. //已选中商品,总价格
  95. if($item['choose'] == 1){
  96. $choose_price_total = bcadd($choose_price_total,$tempData['Price_total'],2);
  97. $choose_number += $tempData['number'];
  98. }
  99. $tempData['product_id'] = Hashids::encodeHex($item['product_id']);
  100. $data[] = $tempData;
  101. }
  102. $result = [
  103. 'choose_price_total' => $choose_price_total,
  104. 'choose_number' => $choose_number,
  105. 'list' => $data,
  106. ];
  107. $this->success('', $result);
  108. }
  109. /**
  110. * @ApiTitle (添加)
  111. * @ApiSummary (添加商品到购物车)
  112. * @ApiMethod (GET)
  113. * @ApiHeaders (name=token, type=string, required=true, description="用户登录的Token", sample="a2e3cc70-d2d1-41e6-9c14-f1d774ee5e1e")
  114. * @ApiHeaders (name=cookie, type=string, required=false, description="用户会话的cookie")
  115. * @ApiParams (name="id", type="string", description="商品id")
  116. * @ApiReturn ({"code":1,"msg":"添加成功","data":1})
  117. */
  118. public function add()
  119. {
  120. $id = input('id', 0);
  121. $number = input('number',1);
  122. $id = \addons\unishop\extend\Hashids::decodeHex($id);
  123. $product = (new Product)->where(['id' => $id, 'switch' => Product::SWITCH_ON])->find();
  124. if (!$product) {
  125. $this->error('产品不存在或已下架');
  126. }
  127. $spec = input('spec', '');
  128. $productBase = (new \addons\unishop\extend\Product())->getBaseData($product->getData(), $spec);
  129. if (!$productBase['stock'] || $productBase['stock'] <= 0) {
  130. $this->error('库存不足');
  131. }
  132. $user_id = $this->auth->id;
  133. $cartModel = new \addons\unishop\model\Cart();
  134. $cartModel->where(['user_id' => $user_id, 'product_id' => $id]);
  135. $spec && $cartModel->where('spec', $spec);
  136. $oldCart = $cartModel->find();
  137. if ($oldCart) {
  138. $this->error('商品已存在购物车');
  139. // $oldCart->number++;
  140. // $result = $oldCart->save();
  141. } else {
  142. $cartModel->user_id = $user_id;
  143. $cartModel->product_id = $id;
  144. $spec && $cartModel->spec = $spec;
  145. $cartModel->number = $number;
  146. $cartModel->snapshot = json_encode($product->getData(), true);
  147. $result = $cartModel->save();
  148. }
  149. if ($result) {
  150. $this->success('添加成功', 1);
  151. } else {
  152. $this->error('添加失败');
  153. }
  154. }
  155. /**
  156. * @ApiTitle (删除)
  157. * @ApiSummary (删除购物车的商品支持多个删除用','号隔开购物车id)
  158. * @ApiMethod (POST)
  159. * @ApiHeaders (name=token, type=string, required=true, description="用户登录的Token", sample="a2e3cc70-d2d1-41e6-9c14-f1d774ee5e1e")
  160. * @ApiHeaders (name=cookie, type=string, required=false, description="用户会话的cookie")
  161. * @ApiParams (name="id", type="string", description="购物车id,多个的话用','号隔开")
  162. * @ApiReturn ({"code":1,"msg":"删除成功","data":1})
  163. */
  164. public function delete()
  165. {
  166. $id = input('id', 0);
  167. $userId = $this->auth->id;
  168. $result = CartModel::destroy(function ($query) use ($id, $userId) {
  169. $query->whereIn('id', $id)->where(['user_id' => $userId]);
  170. });
  171. if ($result) {
  172. $this->success('删除成功', 1);
  173. } else {
  174. $this->error('删除失败', 0);
  175. }
  176. }
  177. /**
  178. * @ApiTitle (修改购物车数量)
  179. * @ApiSummary (修改购物车数量)
  180. * @ApiMethod (GET)
  181. * @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
  182. * @ApiParams (name="id", type=integer, required=true, description="购物车id")
  183. * @ApiParams (name="number", type=integer, required=true, description="数量")
  184. * @ApiReturn ({"code":1,"msg":"更改成功","data":数量})
  185. */
  186. public function number_change()
  187. {
  188. $cart_id = input('id', 0);
  189. $number = input('number', 1);
  190. $cart = CartModel::get(['id' => $cart_id, 'user_id' => $this->auth->id]);
  191. if (empty($cart)) {
  192. $this->error('此商品不存在购物车');
  193. }
  194. $cart->number = $number;
  195. $result = $cart->save();
  196. if ($result) {
  197. $this->success('更改成功', $number);
  198. } else {
  199. $this->error('更改失败', $number);
  200. }
  201. }
  202. /**
  203. * @ApiTitle (修改购物车选中状态)
  204. * @ApiSummary (修改购物车选中状态)
  205. * @ApiMethod (POST)
  206. * @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
  207. * @ApiParams (name="trueArr", type=string, required=true, description="选中的购物车id,多个的话用','号隔开")
  208. * @ApiParams (name="falseArr", type=string, required=true, description="不选的购物车id,多个的话用','号隔开")
  209. * @ApiReturn ({"code":1,"msg":"","data":数量})
  210. */
  211. public function choose_change()
  212. {
  213. $trueArr = input('trueArr', false);
  214. $falseArr = input('falseArr', false);
  215. $user_id = $this->auth->id;
  216. try {
  217. $cart = new CartModel();
  218. if ($trueArr) {
  219. $cart->save(['choose' => CartModel::CHOOSE_ON], function ($query) use ($user_id, $trueArr) {
  220. $query->where('user_id', $user_id)->where('id', 'IN', $trueArr);
  221. });
  222. }
  223. if ($falseArr) {
  224. $cart->save(['choose' => CartModel::CHOOSE_OFF], function ($query) use ($user_id, $falseArr) {
  225. $query->where('user_id', $user_id)->where('id', 'IN', $falseArr);
  226. });
  227. }
  228. } catch (Exception $e) {
  229. $this->error('更新失败', 0);
  230. }
  231. $this->success('', 1);
  232. }
  233. }