123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531 |
- <?php
- namespace app\admin\controller\marketing;
- use app\common\controller\Backend;
- use think\Db;
- use Exception;
- use think\exception\DbException;
- use think\exception\PDOException;
- use think\exception\ValidateException;
- /**
- * 营销活动表(整体活动)
- *
- * @icon fa fa-circle-o
- */
- class Discount extends Backend
- {
- /**
- * Discount模型对象
- * @var \app\admin\model\marketing\discount\Discount
- */
- protected $model = null;
- public function _initialize()
- {
- parent::_initialize();
- $this->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);
- }
- }
|