Discount.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. <?php
  2. namespace app\admin\controller\marketing;
  3. use app\common\controller\Backend;
  4. use think\Db;
  5. use Exception;
  6. use think\exception\DbException;
  7. use think\exception\PDOException;
  8. use think\exception\ValidateException;
  9. use app\common\Enum\ChannelEnum;
  10. /**
  11. * 营销活动表(整体活动)
  12. *
  13. * @icon fa fa-circle-o
  14. */
  15. class Discount extends Backend
  16. {
  17. /**
  18. * Discount模型对象
  19. * @var \app\admin\model\marketing\discount\Discount
  20. */
  21. protected $model = null;
  22. public function _initialize()
  23. {
  24. parent::_initialize();
  25. $this->model = new \app\admin\model\marketing\discount\Discount;
  26. // 渠道配置
  27. $this->view->assign("channelList", ChannelEnum::getChannelMap());
  28. $this->assignconfig("channelList", json_encode(ChannelEnum::getChannelMap()));
  29. }
  30. /**
  31. * 规格折扣设置
  32. */
  33. public function spec_discount()
  34. {
  35. $goods_id = $this->request->get('goods_id');
  36. if (!$goods_id) {
  37. $this->error('参数错误');
  38. }
  39. if ($this->request->isAjax()) {
  40. // 处理提交的数据
  41. $specs = $this->request->post('specs', []);
  42. if ($specs) {
  43. $result = [
  44. 'goodsId' => $goods_id,
  45. 'specs' => $specs
  46. ];
  47. $this->success('设置成功', null, $result);
  48. }
  49. $this->error('提交数据失败');
  50. }
  51. // 获取商品信息
  52. $goods = Db::name('shop_goods')->where('id', $goods_id)->find();
  53. if (!$goods) {
  54. $this->error('商品不存在');
  55. }
  56. // 获取规格信息
  57. $goods_skus = Db::name('shop_goods_sku')
  58. ->where('goods_id', $goods_id)
  59. ->select();
  60. // 获取规格属性名称和值
  61. $sku_specs = [];
  62. foreach ($goods_skus as &$sku) {
  63. $sku_id_arr = explode(',', $sku['spec_value_ids']);
  64. // 查询规格名称和值
  65. $spec_values = Db::name('shop_goods_sku_spec')
  66. ->alias('p')
  67. ->field('p.*, sp.name as spec_name, sv.value as spec_value')
  68. ->join('shop_spec sp', 'sp.id=p.spec_id', 'LEFT')
  69. ->join('shop_spec_value sv', 'sv.id=p.spec_value_id', 'LEFT')
  70. ->where('p.id', 'in', $sku_id_arr)
  71. ->select();
  72. $specs_text = [];
  73. foreach ($spec_values as $spec) {
  74. $specs_text[] = $spec['spec_name'] . ':' . $spec['spec_value'];
  75. }
  76. $sku['specs_text'] = implode(' | ', $specs_text);
  77. }
  78. $this->view->assign('goods', $goods);
  79. $this->view->assign('skus', $goods_skus);
  80. return $this->view->fetch();
  81. }
  82. /**
  83. * 添加
  84. *
  85. * @return string
  86. * @throws \think\Exception
  87. */
  88. public function add()
  89. {
  90. if (false === $this->request->isPost()) {
  91. return $this->view->fetch();
  92. }
  93. $params = $this->request->post('row/a');
  94. if (empty($params)) {
  95. $this->error(__('Parameter %s can not be empty', ''));
  96. }
  97. $params = $this->preExcludeFields($params);
  98. if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
  99. $params[$this->dataLimitField] = $this->auth->id;
  100. }
  101. // 处理活动渠道
  102. if (isset($params['channels']) && is_array($params['channels'])) {
  103. $params['channels'] = json_encode($params['channels']);
  104. } else {
  105. $params['channels'] = json_encode([]);
  106. }
  107. // 处理商品ID和商品数量
  108. $goodsIds = isset($params['goods_ids']) ? $params['goods_ids'] : '';
  109. if ($goodsIds) {
  110. $goodsIdArr = explode(',', $goodsIds);
  111. $params['goods_count'] = count($goodsIdArr);
  112. // 存储为JSON格式
  113. $params['goods_ids'] = json_encode($goodsIdArr);
  114. } else {
  115. $params['goods_count'] = 0;
  116. $params['goods_ids'] = '[]';
  117. }
  118. // 设置默认字段值
  119. $params['type'] = isset($params['type']) ? $params['type'] : 'discount';
  120. $params['inner_type'] = isset($params['inner_type']) ? $params['inner_type'] : 0;
  121. // 对于折扣活动,强制设置为指定商品参与
  122. if ($params['type'] == 'discount') {
  123. $params['goods_join_type'] = 2; // 指定商品参与
  124. } else {
  125. $params['goods_join_type'] = isset($params['goods_join_type']) ? $params['goods_join_type'] : 0;
  126. }
  127. // 设置活动状态
  128. $now = time();
  129. $startTime = strtotime($params['start_time']);
  130. $endTime = strtotime($params['end_time']);
  131. if ($startTime > $now) {
  132. $params['activity_status'] = 0; // 未开始
  133. } elseif ($startTime <= $now && $endTime > $now) {
  134. $params['activity_status'] = 1; // 进行中
  135. } else {
  136. $params['activity_status'] = 2; // 已结束
  137. }
  138. $result = false;
  139. Db::startTrans();
  140. try {
  141. // 是否采用模型验证
  142. if ($this->modelValidate) {
  143. $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  144. $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
  145. $this->model->validateFailException()->validate($validate);
  146. }
  147. // 处理商品信息数组
  148. $goodsInfo = isset($params['goods_info']) ? json_decode($params['goods_info'], true) : [];
  149. // 保存活动基本信息
  150. $result = $this->model->allowField(true)->save($params);
  151. // 处理折扣信息
  152. $discountId = $this->model->id;
  153. // 保存规格折扣数据
  154. if ($params['type'] == 'discount' && !empty($goodsInfo)) {
  155. $specsData = [];
  156. foreach ($goodsInfo as $goodsItem) {
  157. if (!isset($goodsItem['goods_id'])) {
  158. continue;
  159. }
  160. $goodsId = $goodsItem['goods_id'];
  161. // 查询商品信息
  162. $goods = Db::name('shop_goods')->where('id', $goodsId)->find();
  163. if (!$goods) {
  164. continue;
  165. }
  166. if ($goodsItem['spec_type'] == 0) { // 单规格商品
  167. if (!isset($goodsItem['discount_price']) || !isset($goodsItem['discount_stocks'])) {
  168. continue;
  169. }
  170. // 获取单规格商品的实际SKU ID
  171. $skuId = isset($goodsItem['sku_id']) ? $goodsItem['sku_id'] : 0;
  172. if ($skuId == 0) {
  173. // 如果没有传SKU ID,查询商品的第一个SKU
  174. $sku = Db::name('shop_goods_sku')->where('goods_id', $goodsId)->find();
  175. $skuId = $sku ? $sku['id'] : 0;
  176. }
  177. $specsData[] = [
  178. 'activity_id' => $discountId,
  179. 'goods_id' => $goodsId,
  180. 'sku_id' => $skuId, // 使用实际的SKU ID
  181. 'discount' => $goodsItem['discount'] ?: round($goodsItem['discount_price'] * 10 / $goods['price'], 1),
  182. 'discount_price' => $goodsItem['discount_price'],
  183. 'stocks' => $goodsItem['discount_stocks'],
  184. 'createtime' => time(),
  185. 'updatetime' => time(),
  186. ];
  187. } else if ($goodsItem['spec_type'] == 1 && isset($goodsItem['spec'])) { // 多规格商品
  188. foreach ($goodsItem['spec'] as $spec) {
  189. if (!isset($spec['sku_id']) || !isset($spec['discount_price']) || !isset($spec['discount_stocks'])) {
  190. continue;
  191. }
  192. // 查询规格原始价格
  193. $skuInfo = Db::name('shop_goods_sku')
  194. ->where(['id' => $spec['sku_id']])
  195. ->find();
  196. if ($skuInfo) {
  197. $specsData[] = [
  198. 'activity_id' => $discountId,
  199. 'goods_id' => $goodsId,
  200. 'sku_id' => $spec['sku_id'],
  201. 'discount' => $spec['discount'] ?: round($spec['discount_price'] * 10 / $skuInfo['price'], 1),
  202. 'discount_price' => $spec['discount_price'],
  203. 'stocks' => $spec['discount_stocks'],
  204. 'createtime' => time(),
  205. 'updatetime' => time(),
  206. ];
  207. }
  208. }
  209. }
  210. }
  211. // 批量插入规格折扣数据
  212. if (!empty($specsData)) {
  213. Db::table('shop_activity_sku')->insertAll($specsData);
  214. }
  215. }
  216. Db::commit();
  217. } catch (ValidateException|PDOException|Exception $e) {
  218. Db::rollback();
  219. $this->error($e->getMessage());
  220. }
  221. if ($result === false) {
  222. $this->error(__('No rows were inserted'));
  223. }
  224. $this->success();
  225. }
  226. /**
  227. * 编辑
  228. *
  229. * @param $ids
  230. * @return string
  231. * @throws DbException
  232. * @throws \think\Exception
  233. */
  234. public function edit($ids = null)
  235. {
  236. $row = $this->model->get($ids);
  237. if (!$row) {
  238. $this->error(__('No Results were found'));
  239. }
  240. $adminIds = $this->getDataLimitAdminIds();
  241. if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
  242. $this->error(__('You have no permission'));
  243. }
  244. if (false === $this->request->isPost()) {
  245. // 解码JSON数据
  246. if ($row['channels']) {
  247. $row['channels'] = json_decode($row['channels'], true);
  248. }
  249. if ($row['goods_ids']) {
  250. $goodsIdArr = json_decode($row['goods_ids'], true);
  251. $row['goods_ids'] = implode(',', $goodsIdArr);
  252. // 获取商品数据
  253. $goodsData = [];
  254. if (!empty($goodsIdArr)) {
  255. $goodsData = Db::name('shop_goods')
  256. ->alias('g')
  257. ->field('g.*, c.name as category_name')
  258. ->join('shop_category c', 'c.id = g.category_id', 'LEFT')
  259. ->where('g.id', 'in', $goodsIdArr)
  260. ->select();
  261. // 处理商品数据,添加category属性
  262. foreach ($goodsData as &$goods) {
  263. $goods['category'] = ['name' => $goods['category_name']];
  264. unset($goods['category_name']);
  265. }
  266. }
  267. $this->view->assign('goodsData', $goodsData);
  268. }
  269. $this->view->assign('row', $row);
  270. return $this->view->fetch();
  271. }
  272. $params = $this->request->post('row/a');
  273. if (empty($params)) {
  274. $this->error(__('Parameter %s can not be empty', ''));
  275. }
  276. $params = $this->preExcludeFields($params);
  277. // 处理活动渠道
  278. if (isset($params['channels']) && is_array($params['channels'])) {
  279. $params['channels'] = json_encode($params['channels']);
  280. } else {
  281. $params['channels'] = json_encode([]);
  282. }
  283. // 处理商品ID和商品数量
  284. $goodsIds = isset($params['goods_ids']) ? $params['goods_ids'] : '';
  285. if ($goodsIds) {
  286. $goodsIdArr = explode(',', $goodsIds);
  287. $params['goods_count'] = count($goodsIdArr);
  288. $params['goods_ids'] = json_encode($goodsIdArr);
  289. } else {
  290. $params['goods_count'] = 0;
  291. $params['goods_ids'] = '[]';
  292. }
  293. // 对于折扣活动,强制设置为指定商品参与
  294. if ($params['type'] == 'discount') {
  295. $params['goods_join_type'] = 2;
  296. }
  297. // 设置活动状态
  298. $now = time();
  299. $startTime = strtotime($params['start_time']);
  300. $endTime = strtotime($params['end_time']);
  301. if ($startTime > $now) {
  302. $params['activity_status'] = 0; // 未开始
  303. } elseif ($startTime <= $now && $endTime > $now) {
  304. $params['activity_status'] = 1; // 进行中
  305. } else {
  306. $params['activity_status'] = 2; // 已结束
  307. }
  308. $result = false;
  309. Db::startTrans();
  310. try {
  311. //是否采用模型验证
  312. if ($this->modelValidate) {
  313. $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  314. $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
  315. $row->validateFailException()->validate($validate);
  316. }
  317. $result = $row->allowField(true)->save($params);
  318. // 处理折扣数据
  319. if ($params['type'] == 'discount') {
  320. // 处理商品信息数组
  321. $goodsInfo = isset($params['goods_info']) ? json_decode($params['goods_info'], true) : [];
  322. \think\Log::write('编辑时商品信息数组: ' . json_encode($goodsInfo), 'debug');
  323. // 删除旧的规格折扣数据
  324. Db::name('shop_activity_sku')->where('activity_id', $ids)->delete();
  325. // 准备新的规格折扣数据
  326. if (!empty($goodsInfo)) {
  327. $specsData = [];
  328. foreach ($goodsInfo as $goodsItem) {
  329. if (!isset($goodsItem['goods_id'])) {
  330. continue;
  331. }
  332. $goodsId = $goodsItem['goods_id'];
  333. // 查询商品信息
  334. $goods = Db::name('shop_goods')->where('id', $goodsId)->find();
  335. if (!$goods) {
  336. continue;
  337. }
  338. if ($goodsItem['spec_type'] == 0) { // 单规格商品
  339. if (!isset($goodsItem['discount_price']) || !isset($goodsItem['discount_stocks'])) {
  340. continue;
  341. }
  342. // 获取单规格商品的实际SKU ID
  343. $skuId = isset($goodsItem['sku_id']) ? $goodsItem['sku_id'] : 0;
  344. if ($skuId == 0) {
  345. // 如果没有传SKU ID,查询商品的第一个SKU
  346. $sku = Db::name('shop_goods_sku')->where('goods_id', $goodsId)->find();
  347. $skuId = $sku ? $sku['id'] : 0;
  348. }
  349. $specsData[] = [
  350. 'activity_id' => $ids,
  351. 'goods_id' => $goodsId,
  352. 'sku_id' => $skuId, // 使用实际的SKU ID
  353. 'discount' => $goodsItem['discount'] ?: round($goodsItem['discount_price'] * 10 / $goods['price'], 1),
  354. 'discount_price' => $goodsItem['discount_price'],
  355. 'stocks' => $goodsItem['discount_stocks'],
  356. 'createtime' => time(),
  357. 'updatetime' => time(),
  358. ];
  359. } else if ($goodsItem['spec_type'] == 1 && isset($goodsItem['spec'])) { // 多规格商品
  360. foreach ($goodsItem['spec'] as $spec) {
  361. if (!isset($spec['sku_id']) || !isset($spec['discount_price']) || !isset($spec['discount_stocks'])) {
  362. continue;
  363. }
  364. // 查询规格原始价格
  365. $skuInfo = Db::name('shop_goods_sku')
  366. ->where(['id' => $spec['sku_id']])
  367. ->find();
  368. if ($skuInfo) {
  369. $specsData[] = [
  370. 'activity_id' => $ids,
  371. 'goods_id' => $goodsId,
  372. 'sku_id' => $spec['sku_id'],
  373. 'discount' => $spec['discount'] ?: round($spec['discount_price'] * 10 / $skuInfo['price'], 1),
  374. 'discount_price' => $spec['discount_price'],
  375. 'stocks' => $spec['discount_stocks'],
  376. 'createtime' => time(),
  377. 'updatetime' => time(),
  378. ];
  379. }
  380. }
  381. }
  382. }
  383. // 批量插入规格折扣数据
  384. if (!empty($specsData)) {
  385. Db::name('shop_activity_sku')->insertAll($specsData);
  386. }
  387. }
  388. }
  389. Db::commit();
  390. } catch (ValidateException|PDOException|Exception $e) {
  391. Db::rollback();
  392. $this->error($e->getMessage());
  393. }
  394. if (false === $result) {
  395. $this->error(__('No rows were updated'));
  396. }
  397. $this->success();
  398. }
  399. /**
  400. * 手动停止活动
  401. */
  402. public function stopActivity()
  403. {
  404. $id = $this->request->post('id');
  405. $activity = $this->model->find($id);
  406. if (!$activity) {
  407. $this->error('活动不存在');
  408. }
  409. if ($activity['activity_status'] != 1) {
  410. $this->error('只有进行中的活动才能手动停止');
  411. }
  412. // 设置停止时间和状态
  413. $activity->stop_time = date('Y-m-d H:i:s');
  414. $activity->activity_status = 3; // 手动停止
  415. if ($activity->save()) {
  416. $this->success('活动已手动停止');
  417. } else {
  418. $this->error('操作失败');
  419. }
  420. }
  421. /**
  422. * 更新活动状态
  423. * 可作为定时任务
  424. */
  425. public function updateActivityStatus()
  426. {
  427. $now = date('Y-m-d H:i:s');
  428. // 更新未开始的活动
  429. Db::name('shop_discount')
  430. ->where([
  431. 'status' => 1, // 启用状态
  432. 'activity_status' => ['IN', [0, 3]], // 未开始或手动停止
  433. 'start_time' => ['<=', $now],
  434. 'end_time' => ['>', $now],
  435. 'stop_time' => ['exp', Db::raw('IS NULL OR stop_time > NOW()')],
  436. ])
  437. ->update(['activity_status' => 1]); // 更新为进行中
  438. // 更新已结束的活动
  439. Db::name('shop_discount')
  440. ->where([
  441. 'status' => 1, // 启用状态
  442. 'activity_status' => 1, // 进行中
  443. ])
  444. ->where(function($query) use ($now) {
  445. $query->where('end_time', '<=', $now)
  446. ->whereOr('stop_time', '<=', $now);
  447. })
  448. ->update(['activity_status' => 2]); // 更新为已结束
  449. $this->success('活动状态更新完成');
  450. }
  451. /**
  452. * 获取活动商品的折扣和库存数据
  453. */
  454. public function get_discount_specs()
  455. {
  456. $discountId = $this->request->get('discount_id');
  457. if (!$discountId) {
  458. $this->error('参数错误');
  459. }
  460. // 查询折扣数据
  461. $discountSpecs = Db::name('shop_activity_sku_prize')
  462. ->where('discount_id', $discountId)
  463. ->select();
  464. $this->success('', null, $discountSpecs);
  465. }
  466. }