Cart.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. /**
  3. *
  4. * @copyright ©2020 点小铺
  5. * @author hanj
  6. * @link: https://dyuit.com
  7. * Created by VSCode
  8. */
  9. namespace app\api\controller;
  10. use app\api\model\Cart as CartModel;
  11. use app\api\service\order\Checkout as CheckoutModel;
  12. /**
  13. * 购物车管理
  14. * Class Cart
  15. * @package app\api\controller
  16. */
  17. class Cart extends Controller
  18. {
  19. /* @var \app\api\model\User $user */
  20. private $user;
  21. /* @var \app\api\model\Cart $model */
  22. private $model;
  23. /**
  24. * 构造方法
  25. * @throws \app\common\exception\BaseException
  26. * @throws \think\exception\DbException
  27. */
  28. public function _initialize()
  29. {
  30. parent::_initialize();
  31. $this->user = $this->getUser();
  32. $this->model = new CartModel($this->user);
  33. }
  34. /**
  35. * 购物车列表
  36. * @return array
  37. * @throws \think\Exception
  38. * @throws \think\db\exception\DataNotFoundException
  39. * @throws \think\db\exception\ModelNotFoundException
  40. * @throws \think\exception\DbException
  41. */
  42. public function lists()
  43. {
  44. // 请求参数
  45. $param = $this->request->param();
  46. $cartIds = isset($param['cart_ids']) ? $param['cart_ids'] : '';
  47. // 购物车商品列表
  48. $goodsList = $this->model->getList($cartIds);
  49. // 获取订单结算信息
  50. $Checkout = new CheckoutModel;
  51. $orderInfo = $Checkout->onCheckout($this->user, $goodsList);
  52. return $this->renderSuccess($orderInfo);
  53. }
  54. /**
  55. * 加入购物车
  56. * @param int $goods_id 商品id
  57. * @param int $goods_num 商品数量
  58. * @param string $goods_sku_id 商品sku索引
  59. * @return array
  60. * @throws \app\common\exception\BaseException
  61. * @throws \think\exception\DbException
  62. */
  63. public function add($goods_id, $goods_num, $goods_sku_id)
  64. {
  65. if (!$this->model->add($goods_id, $goods_num, $goods_sku_id)) {
  66. return $this->renderError($this->model->getError() ?: '加入购物车失败');
  67. }
  68. // 购物车商品总数量
  69. $totalNum = $this->model->getGoodsNum();
  70. return $this->renderSuccess(['cart_total_num' => $totalNum], '加入购物车成功');
  71. }
  72. /**
  73. * 减少购物车商品数量
  74. * @param $goods_id
  75. * @param $goods_sku_id
  76. * @return array
  77. */
  78. public function sub($goods_id, $goods_sku_id)
  79. {
  80. $this->model->sub($goods_id, $goods_sku_id);
  81. return $this->renderSuccess();
  82. }
  83. /**
  84. * 删除购物车中指定商品
  85. * @param $goods_sku_id (支持字符串ID集)
  86. * @return array
  87. */
  88. public function delete($goods_sku_id)
  89. {
  90. $this->model->delete($goods_sku_id);
  91. return $this->renderSuccess();
  92. }
  93. }