Cart.php 9.8 KB

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