model = new \app\admin\model\marketing\discount\Discount; } /** * 规格折扣设置 */ public function spec_discount() { $goods_id = $this->request->get('goods_id'); if (!$goods_id) { $this->error('参数错误'); } if ($this->request->isAjax()) { // 处理提交的数据 $specs = $this->request->post('specs', []); if ($specs) { $result = [ 'goodsId' => $goods_id, 'specs' => $specs ]; $this->success('设置成功', null, $result); } $this->error('提交数据失败'); } // 获取商品信息 $goods = Db::name('shop_goods')->where('id', $goods_id)->find(); if (!$goods) { $this->error('商品不存在'); } // 获取规格信息 $goods_skus = Db::name('shop_goods_sku') ->where('goods_id', $goods_id) ->select(); // 获取规格属性名称和值 $sku_specs = []; foreach ($goods_skus as &$sku) { $sku_id_arr = explode(',', $sku['spec_value_ids']); // 查询规格名称和值 $spec_values = Db::name('shop_goods_sku_spec') ->alias('p') ->field('p.*, sp.name as spec_name, sv.value as spec_value') ->join('shop_spec sp', 'sp.id=p.spec_id', 'LEFT') ->join('shop_spec_value sv', 'sv.id=p.spec_value_id', 'LEFT') ->where('p.id', 'in', $sku_id_arr) ->select(); $specs_text = []; foreach ($spec_values as $spec) { $specs_text[] = $spec['spec_name'] . ':' . $spec['spec_value']; } $sku['specs_text'] = implode(' | ', $specs_text); } $this->view->assign('goods', $goods); $this->view->assign('skus', $goods_skus); return $this->view->fetch(); } /** * 添加 * * @return string * @throws \think\Exception */ public function add() { if (false === $this->request->isPost()) { return $this->view->fetch(); } $params = $this->request->post('row/a'); if (empty($params)) { $this->error(__('Parameter %s can not be empty', '')); } $params = $this->preExcludeFields($params); if ($this->dataLimit && $this->dataLimitFieldAutoFill) { $params[$this->dataLimitField] = $this->auth->id; } // 处理活动渠道 if (isset($params['channels']) && is_array($params['channels'])) { $params['channels'] = json_encode($params['channels']); } else { $params['channels'] = json_encode([]); } // 处理商品ID和商品数量 $goodsIds = isset($params['goods_ids']) ? $params['goods_ids'] : ''; if ($goodsIds) { $goodsIdArr = explode(',', $goodsIds); $params['goods_count'] = count($goodsIdArr); // 存储为JSON格式 $params['goods_ids'] = json_encode($goodsIdArr); } else { $params['goods_count'] = 0; $params['goods_ids'] = '[]'; } // 设置默认字段值 $params['type'] = isset($params['type']) ? $params['type'] : 'discount'; $params['inner_type'] = isset($params['inner_type']) ? $params['inner_type'] : 0; // 对于折扣活动,强制设置为指定商品参与 if ($params['type'] == 'discount') { $params['goods_join_type'] = 2; // 指定商品参与 } else { $params['goods_join_type'] = isset($params['goods_join_type']) ? $params['goods_join_type'] : 0; } // 设置活动状态 $now = time(); $startTime = strtotime($params['start_time']); $endTime = strtotime($params['end_time']); if ($startTime > $now) { $params['activity_status'] = 0; // 未开始 } elseif ($startTime <= $now && $endTime > $now) { $params['activity_status'] = 1; // 进行中 } else { $params['activity_status'] = 2; // 已结束 } $result = false; Db::startTrans(); try { // 是否采用模型验证 if ($this->modelValidate) { $name = str_replace("\\model\\", "\\validate\\", get_class($this->model)); $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate; $this->model->validateFailException()->validate($validate); } // 处理商品信息数组 $goodsInfo = isset($params['goods_info']) ? json_decode($params['goods_info'], true) : []; // 保存活动基本信息 $result = $this->model->allowField(true)->save($params); // 处理折扣信息 $discountId = $this->model->id; // 保存规格折扣数据 if ($params['type'] == 'discount' && !empty($goodsInfo)) { $specsData = []; foreach ($goodsInfo as $goodsItem) { if (!isset($goodsItem['goods_id'])) { continue; } $goodsId = $goodsItem['goods_id']; // 查询商品信息 $goods = Db::name('shop_goods')->where('id', $goodsId)->find(); if (!$goods) { continue; } if ($goodsItem['spec_type'] == 0) { // 单规格商品 if (!isset($goodsItem['discount_price']) || !isset($goodsItem['discount_stocks'])) { continue; } // 获取单规格商品的实际SKU ID $skuId = isset($goodsItem['sku_id']) ? $goodsItem['sku_id'] : 0; if ($skuId == 0) { // 如果没有传SKU ID,查询商品的第一个SKU $sku = Db::name('shop_goods_sku')->where('goods_id', $goodsId)->find(); $skuId = $sku ? $sku['id'] : 0; } $specsData[] = [ 'activity_id' => $discountId, 'goods_id' => $goodsId, 'sku_id' => $skuId, // 使用实际的SKU ID 'discount' => $goodsItem['discount'] ?: round($goodsItem['discount_price'] * 10 / $goods['price'], 1), 'discount_price' => $goodsItem['discount_price'], 'stocks' => $goodsItem['discount_stocks'], 'createtime' => time(), 'updatetime' => time(), ]; } else if ($goodsItem['spec_type'] == 1 && isset($goodsItem['spec'])) { // 多规格商品 foreach ($goodsItem['spec'] as $spec) { if (!isset($spec['sku_id']) || !isset($spec['discount_price']) || !isset($spec['discount_stocks'])) { continue; } // 查询规格原始价格 $skuInfo = Db::name('shop_goods_sku') ->where(['id' => $spec['sku_id']]) ->find(); if ($skuInfo) { $specsData[] = [ 'activity_id' => $discountId, 'goods_id' => $goodsId, 'sku_id' => $spec['sku_id'], 'discount' => $spec['discount'] ?: round($spec['discount_price'] * 10 / $skuInfo['price'], 1), 'discount_price' => $spec['discount_price'], 'stocks' => $spec['discount_stocks'], 'createtime' => time(), 'updatetime' => time(), ]; } } } } // 批量插入规格折扣数据 if (!empty($specsData)) { Db::table('shop_activity_sku')->insertAll($specsData); } } Db::commit(); } catch (ValidateException|PDOException|Exception $e) { Db::rollback(); $this->error($e->getMessage()); } if ($result === false) { $this->error(__('No rows were inserted')); } $this->success(); } /** * 编辑 * * @param $ids * @return string * @throws DbException * @throws \think\Exception */ public function edit($ids = null) { $row = $this->model->get($ids); if (!$row) { $this->error(__('No Results were found')); } $adminIds = $this->getDataLimitAdminIds(); if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) { $this->error(__('You have no permission')); } if (false === $this->request->isPost()) { // 解码JSON数据 if ($row['channels']) { $row['channels'] = json_decode($row['channels'], true); } if ($row['goods_ids']) { $goodsIdArr = json_decode($row['goods_ids'], true); $row['goods_ids'] = implode(',', $goodsIdArr); // 获取商品数据 $goodsData = []; if (!empty($goodsIdArr)) { $goodsData = Db::name('shop_goods') ->alias('g') ->field('g.*, c.name as category_name') ->join('shop_category c', 'c.id = g.category_id', 'LEFT') ->where('g.id', 'in', $goodsIdArr) ->select(); // 处理商品数据,添加category属性 foreach ($goodsData as &$goods) { $goods['category'] = ['name' => $goods['category_name']]; unset($goods['category_name']); } } $this->view->assign('goodsData', $goodsData); } $this->view->assign('row', $row); return $this->view->fetch(); } $params = $this->request->post('row/a'); if (empty($params)) { $this->error(__('Parameter %s can not be empty', '')); } $params = $this->preExcludeFields($params); // 处理活动渠道 if (isset($params['channels']) && is_array($params['channels'])) { $params['channels'] = json_encode($params['channels']); } else { $params['channels'] = json_encode([]); } // 处理商品ID和商品数量 $goodsIds = isset($params['goods_ids']) ? $params['goods_ids'] : ''; if ($goodsIds) { $goodsIdArr = explode(',', $goodsIds); $params['goods_count'] = count($goodsIdArr); $params['goods_ids'] = json_encode($goodsIdArr); } else { $params['goods_count'] = 0; $params['goods_ids'] = '[]'; } // 对于折扣活动,强制设置为指定商品参与 if ($params['type'] == 'discount') { $params['goods_join_type'] = 2; } // 设置活动状态 $now = time(); $startTime = strtotime($params['start_time']); $endTime = strtotime($params['end_time']); if ($startTime > $now) { $params['activity_status'] = 0; // 未开始 } elseif ($startTime <= $now && $endTime > $now) { $params['activity_status'] = 1; // 进行中 } else { $params['activity_status'] = 2; // 已结束 } $result = false; Db::startTrans(); try { //是否采用模型验证 if ($this->modelValidate) { $name = str_replace("\\model\\", "\\validate\\", get_class($this->model)); $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate; $row->validateFailException()->validate($validate); } $result = $row->allowField(true)->save($params); // 处理折扣数据 if ($params['type'] == 'discount') { // 处理商品信息数组 $goodsInfo = isset($params['goods_info']) ? json_decode($params['goods_info'], true) : []; \think\Log::write('编辑时商品信息数组: ' . json_encode($goodsInfo), 'debug'); // 删除旧的规格折扣数据 Db::name('shop_activity_sku')->where('activity_id', $ids)->delete(); // 准备新的规格折扣数据 if (!empty($goodsInfo)) { $specsData = []; foreach ($goodsInfo as $goodsItem) { if (!isset($goodsItem['goods_id'])) { continue; } $goodsId = $goodsItem['goods_id']; // 查询商品信息 $goods = Db::name('shop_goods')->where('id', $goodsId)->find(); if (!$goods) { continue; } if ($goodsItem['spec_type'] == 0) { // 单规格商品 if (!isset($goodsItem['discount_price']) || !isset($goodsItem['discount_stocks'])) { continue; } // 获取单规格商品的实际SKU ID $skuId = isset($goodsItem['sku_id']) ? $goodsItem['sku_id'] : 0; if ($skuId == 0) { // 如果没有传SKU ID,查询商品的第一个SKU $sku = Db::name('shop_goods_sku')->where('goods_id', $goodsId)->find(); $skuId = $sku ? $sku['id'] : 0; } $specsData[] = [ 'activity_id' => $ids, 'goods_id' => $goodsId, 'sku_id' => $skuId, // 使用实际的SKU ID 'discount' => $goodsItem['discount'] ?: round($goodsItem['discount_price'] * 10 / $goods['price'], 1), 'discount_price' => $goodsItem['discount_price'], 'stocks' => $goodsItem['discount_stocks'], 'createtime' => time(), 'updatetime' => time(), ]; } else if ($goodsItem['spec_type'] == 1 && isset($goodsItem['spec'])) { // 多规格商品 foreach ($goodsItem['spec'] as $spec) { if (!isset($spec['sku_id']) || !isset($spec['discount_price']) || !isset($spec['discount_stocks'])) { continue; } // 查询规格原始价格 $skuInfo = Db::name('shop_goods_sku') ->where(['id' => $spec['sku_id']]) ->find(); if ($skuInfo) { $specsData[] = [ 'activity_id' => $ids, 'goods_id' => $goodsId, 'sku_id' => $spec['sku_id'], 'discount' => $spec['discount'] ?: round($spec['discount_price'] * 10 / $skuInfo['price'], 1), 'discount_price' => $spec['discount_price'], 'stocks' => $spec['discount_stocks'], 'createtime' => time(), 'updatetime' => time(), ]; } } } } // 批量插入规格折扣数据 if (!empty($specsData)) { Db::name('shop_activity_sku')->insertAll($specsData); } } } Db::commit(); } catch (ValidateException|PDOException|Exception $e) { Db::rollback(); $this->error($e->getMessage()); } if (false === $result) { $this->error(__('No rows were updated')); } $this->success(); } /** * 手动停止活动 */ public function stopActivity() { $id = $this->request->post('id'); $activity = $this->model->find($id); if (!$activity) { $this->error('活动不存在'); } if ($activity['activity_status'] != 1) { $this->error('只有进行中的活动才能手动停止'); } // 设置停止时间和状态 $activity->stop_time = date('Y-m-d H:i:s'); $activity->activity_status = 3; // 手动停止 if ($activity->save()) { $this->success('活动已手动停止'); } else { $this->error('操作失败'); } } /** * 更新活动状态 * 可作为定时任务 */ public function updateActivityStatus() { $now = date('Y-m-d H:i:s'); // 更新未开始的活动 Db::name('shop_discount') ->where([ 'status' => 1, // 启用状态 'activity_status' => ['IN', [0, 3]], // 未开始或手动停止 'start_time' => ['<=', $now], 'end_time' => ['>', $now], 'stop_time' => ['exp', Db::raw('IS NULL OR stop_time > NOW()')], ]) ->update(['activity_status' => 1]); // 更新为进行中 // 更新已结束的活动 Db::name('shop_discount') ->where([ 'status' => 1, // 启用状态 'activity_status' => 1, // 进行中 ]) ->where(function($query) use ($now) { $query->where('end_time', '<=', $now) ->whereOr('stop_time', '<=', $now); }) ->update(['activity_status' => 2]); // 更新为已结束 $this->success('活动状态更新完成'); } /** * 获取活动商品的折扣和库存数据 */ public function get_discount_specs() { $discountId = $this->request->get('discount_id'); if (!$discountId) { $this->error('参数错误'); } // 查询折扣数据 $discountSpecs = Db::name('shop_activity_sku_prize') ->where('discount_id', $discountId) ->select(); $this->success('', null, $discountSpecs); } }