Discount.php 20 KB

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