120 lines
3.4 KiB
PHP
120 lines
3.4 KiB
PHP
<?php
|
|
|
|
/**
|
|
* @author Any
|
|
* @description KISS
|
|
* @date 2021年6月15日
|
|
* @version 1.0.0
|
|
*
|
|
* _____LOG_____
|
|
*
|
|
*/
|
|
namespace app\models\common;
|
|
|
|
|
|
use app\models\Cart;
|
|
use app\models\Goods;
|
|
use app\models\GoodsAttr;
|
|
use app\models\Model;
|
|
use yii\helpers\ArrayHelper;
|
|
use app\components\Serializer;
|
|
|
|
class CommonCartAddForm extends Model
|
|
{
|
|
public $goods_id;
|
|
public $attr;
|
|
public $num;
|
|
|
|
public $plugin_sign;
|
|
public $cx_mch_id;
|
|
public $user_id;
|
|
|
|
public function rules()
|
|
{
|
|
return [
|
|
[['goods_id', 'num', 'attr', 'cx_mch_id', 'user_id'], 'integer'],
|
|
[['cx_mch_id', 'user_id', 'goods_id', 'attr', 'num', 'plugin_sign'], 'required']
|
|
];
|
|
}
|
|
|
|
public function save()
|
|
{
|
|
|
|
if (!$this->validate()) {
|
|
return $this->getModelError();
|
|
}
|
|
|
|
try {
|
|
Cart::cacheStatusSet(true);
|
|
$goods = Goods::findOne(['id' => $this->goods_id]);
|
|
if (!$goods) {
|
|
throw new \Exception('商品不存在');
|
|
}
|
|
if ($goods->goodsHub->type == 1) {
|
|
throw new \Exception('虚拟商品不允许加入购物车');
|
|
}
|
|
|
|
$attr = GoodsAttr::find()->alias('g')->where([
|
|
'g.id' => $this->attr,
|
|
'g.goods_id' => $this->goods_id,
|
|
'g.is_delete' => 0,
|
|
])->innerJoinwith(['goods o' => function ($query) {
|
|
$query->where([
|
|
'o.id' => $this->goods_id,
|
|
'o.cx_mch_id' => $this->cx_mch_id,
|
|
'o.is_delete' => 0,
|
|
'o.status' => 1,
|
|
]);
|
|
}])->one();
|
|
|
|
if (!$attr) {
|
|
throw new \Exception('商品异常');
|
|
}
|
|
|
|
$this->num = $this->num > $attr->stock ? $attr->stock : $this->num;
|
|
if ($this->num <= 0) {
|
|
throw new \Exception('数量为空或库存为空');
|
|
}
|
|
|
|
$cart = Cart::findOne([
|
|
'user_id' => $this->user_id,
|
|
'goods_id' => $this->goods_id,
|
|
'attr_id' => $this->attr,
|
|
'cx_mch_id' => $this->cx_mch_id,
|
|
'plugin_sign' => $this->plugin_sign,
|
|
'is_delete' => 0,
|
|
]);
|
|
|
|
if (!$cart) {
|
|
$cart = new Cart();
|
|
$cart->user_id = $this->user_id;
|
|
$cart->goods_id = $this->goods_id;
|
|
$cart->attr_id = $this->attr;
|
|
$cart->num = 0;
|
|
$cart->cx_mch_id = $this->cx_mch_id;
|
|
$cart->plugin_sign = $this->plugin_sign;
|
|
$cart->attr_info = (new Serializer())->encode(ArrayHelper::toArray($attr));
|
|
};
|
|
$cart->num += $this->num;
|
|
if ($cart->num > $attr->stock) {
|
|
return $this->apiReturnError('商品加购件数超过库存');
|
|
}
|
|
|
|
if ($cart->save()) {
|
|
return $this->apiReturnSuccess('添加购物车成功');
|
|
} else {
|
|
throw new \Exception($this->getModelError($cart));
|
|
}
|
|
} catch (\Exception $e) {
|
|
return $this->apiReturnError($e->getMessage());
|
|
}
|
|
}
|
|
|
|
|
|
public function __destruct()
|
|
{
|
|
Cart::cacheStatusSet(false);
|
|
}
|
|
}
|
|
|