| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119 |
- <?php
- /**
- * 重庆赤晓店信息科技有限公司
- * https://www.chixiaodian.com
- * Copyright (c) 2023 赤店商城 All rights reserved.
- */
- namespace app\modules\alliance\models;
- use app\models\Cart;
- use app\models\FoodCart;
- use app\models\FoodFlag;
- use app\models\Goods;
- use yii\base\BaseObject;
- use yii\base\Model;
- class FoodAddCartForm extends Model
- {
- public $user_id;
- public $saas_id;
- public $store_id;
- public $goods_id;
- public $attr;
- public $num;
- public $md_id;
- public $flag_id;
- public function rules()
- {
- return [
- [['goods_id', 'attr', 'num', 'md_id'], 'required'],
- [['goods_id', 'num', 'flag_id'], 'integer'],
- [['num'], 'integer', 'min' => 1],
- ];
- }
- public function save()
- {
- try {
- if (!$this->validate()) {
- return [
- 'code' => 1,
- 'msg' => $this->getErrorSummary(false)[0]
- ];
- }
- $goods = Goods::findOne([
- 'id' => $this->goods_id,
- 'store_id' => $this->store_id,
- 'is_delete' => 0,
- 'status' => 1,
- ]);
- if (!$goods) {
- return [
- 'code' => 1,
- 'msg' => '商品不存在或已下架',
- ];
- }
- $this->attr = json_decode($this->attr, true);
- $attr = [];
- foreach ($this->attr as $item) {
- if (!empty($item['attr_id'])) {
- $attr[] = intval($item['attr_id']);
- }
- }
- sort($attr);
- $attr = json_encode($attr, JSON_UNESCAPED_UNICODE);
- $food_flag = FoodFlag::findOne($this->flag_id);
- $cart = FoodCart::findOne([
- 'goods_id' => $this->goods_id,
- 'user_id' => $this->user_id,
- 'saas_id' => $this->saas_id,
- 'is_delete' => 0,
- 'attr' => $attr,
- 'flag_id' => $this->flag_id
- ]);
- if (!$cart) {
- $cart = new FoodCart();
- $cart->goods_id = $this->goods_id;
- $cart->user_id = $this->user_id;
- $cart->saas_id = $this->saas_id;
- $cart->num = 0;
- $cart->flag_id = $this->flag_id;
- $cart->created_at = time();
- $cart->is_delete = 0;
- $cart->attr = $attr;
- }
- $cart->status = 1;
- if ($food_flag->user_id == $this->user_id || $food_flag->type == 1) {
- $cart->status = 1;
- }
- $cart->num += $this->num;
- $cart_num = FoodCart::find()->where(['flag_id' => $this->flag_id, 'goods_id' => $this->goods_id, 'is_delete' => 0])->sum('num');
- if (($cart_num + $cart->num) > $goods->goods_num) {
- return [
- 'code' => 1,
- 'msg' => '库存不足',
- ];
- }
- if ($cart->save()) {
- return [
- 'code' => 0,
- 'msg' => '添加购物车成功',
- 'data' => [
- 'flag_id' => $this->flag_id
- ],
- ];
- } else {
- return ['code' => 1, 'msg' => $cart->errors];
- }
- } catch (\Exception $e) {
- return [
- 'code' => 1,
- 'msg' => $e->getMessage() . 'line=' . $e->getLine()
- ];
- }
- }
- }
|