CsAgentCartController.php 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace addons\CloudStock\api\modules\v1\controllers;
  3. use addons\CloudStock\common\models\CloudStockAgentCart;
  4. use addons\CloudStock\common\services\CloudStockAgentCartService;
  5. use addons\CloudStock\common\services\CloudStockAgentGoodsService;
  6. use addons\CloudStock\common\services\CloudStockAgentOrderService;
  7. use addons\CloudStock\common\services\CloudStockLevelService;
  8. use common\enums\StatusEnum;
  9. use Exception;
  10. use Yii;
  11. class CsAgentCartController extends BaseController
  12. {
  13. public $modelClass = '';
  14. protected $authOptional = [];
  15. /**
  16. * @return mixed|void|null
  17. */
  18. public function actionSetCart()
  19. {
  20. $post = $this->request->post();
  21. $rules = [
  22. [['goods_id', 'num'], 'required'],
  23. [['goods_id', 'num'], 'integer'],
  24. ];
  25. $res = Yii::$app->services->validate->validate($post, $rules);
  26. if ($res === false) {
  27. return $this->error(Yii::$app->services->validate->getErrorMessage());
  28. }
  29. $baseParams = ['user_id' => $this->user_id, 'mall_id' => $this->mall_id, 'stock_agent' => $this->stock_agent];
  30. $goodsService = new CloudStockAgentGoodsService($baseParams);
  31. $cartService = new CloudStockAgentCartService($baseParams);
  32. $orderService = new CloudStockAgentOrderService($baseParams);
  33. $levelService = new CloudStockLevelService($baseParams);
  34. if (!$goodsService->goodsExist($post['goods_id'])) {
  35. $this->error('商品不存在');
  36. return;
  37. }
  38. $currentCart = $cartService->getCartList([$post['goods_id']]);
  39. $currentNum = array_column($currentCart, 'num', 'goods_id')[$post['goods_id']] ?? 0;
  40. // 如果是增加购物车才验证,如果是减购物车则不理
  41. if ($post['num'] > $currentNum) {
  42. $cartList = [
  43. ['num' => $post['num'], 'goods_id' => $post['goods_id']]
  44. ];
  45. // 验证限购(不能超过代理商品的总库存 不能超过后台限制的配置)
  46. if (!$orderService->checkLimit($cartService, $levelService, $goodsService, $cartList, false)) {
  47. $this->error($orderService->getError());
  48. return;
  49. }
  50. }
  51. $post = array_merge($post, $baseParams);
  52. if (!CloudStockAgentCart::setCart($post)) {
  53. $this->error('加入购物车异常');
  54. return;
  55. }
  56. $this->success();
  57. }
  58. /**
  59. * 返回加购的数量
  60. *
  61. * @return void
  62. */
  63. public function actionCartInfo()
  64. {
  65. $baseParams = ['user_id' => $this->user_id, 'mall_id' => $this->mall_id];
  66. $cartService = new CloudStockAgentCartService($baseParams);
  67. $this->success('success', ['cart_count' => $cartService->getCurrentCartCount(), 'cart_list' => $cartService->getCartList()]);
  68. }
  69. }