Discount.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  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['spec_value_ids']);
  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. // 获取单规格商品的实际SKU ID
  167. $skuId = isset($goodsItem['sku_id']) ? $goodsItem['sku_id'] : 0;
  168. if ($skuId == 0) {
  169. // 如果没有传SKU ID,查询商品的第一个SKU
  170. $sku = Db::name('shop_goods_sku')->where('goods_id', $goodsId)->find();
  171. $skuId = $sku ? $sku['id'] : 0;
  172. }
  173. $specsData[] = [
  174. 'activity_id' => $discountId,
  175. 'goods_id' => $goodsId,
  176. 'sku_id' => $skuId, // 使用实际的SKU ID
  177. 'discount' => $goodsItem['discount'] ?: round($goodsItem['discount_price'] * 10 / $goods['price'], 1),
  178. 'discount_price' => $goodsItem['discount_price'],
  179. 'stocks' => $goodsItem['discount_stocks'],
  180. 'createtime' => time(),
  181. 'updatetime' => time(),
  182. ];
  183. } else if ($goodsItem['spec_type'] == 1 && isset($goodsItem['spec'])) { // 多规格商品
  184. foreach ($goodsItem['spec'] as $spec) {
  185. if (!isset($spec['sku_id']) || !isset($spec['discount_price']) || !isset($spec['discount_stocks'])) {
  186. continue;
  187. }
  188. // 查询规格原始价格
  189. $skuInfo = Db::name('shop_goods_sku')
  190. ->where(['id' => $spec['sku_id']])
  191. ->find();
  192. if ($skuInfo) {
  193. $specsData[] = [
  194. 'activity_id' => $discountId,
  195. 'goods_id' => $goodsId,
  196. 'sku_id' => $spec['sku_id'],
  197. 'discount' => $spec['discount'] ?: round($spec['discount_price'] * 10 / $skuInfo['price'], 1),
  198. 'discount_price' => $spec['discount_price'],
  199. 'stocks' => $spec['discount_stocks'],
  200. 'createtime' => time(),
  201. 'updatetime' => time(),
  202. ];
  203. }
  204. }
  205. }
  206. }
  207. // 批量插入规格折扣数据
  208. if (!empty($specsData)) {
  209. Db::table('shop_activity_sku')->insertAll($specsData);
  210. }
  211. }
  212. Db::commit();
  213. } catch (ValidateException|PDOException|Exception $e) {
  214. Db::rollback();
  215. $this->error($e->getMessage());
  216. }
  217. if ($result === false) {
  218. $this->error(__('No rows were inserted'));
  219. }
  220. $this->success();
  221. }
  222. /**
  223. * 编辑
  224. *
  225. * @param $ids
  226. * @return string
  227. * @throws DbException
  228. * @throws \think\Exception
  229. */
  230. public function edit($ids = null)
  231. {
  232. $row = $this->model->get($ids);
  233. if (!$row) {
  234. $this->error(__('No Results were found'));
  235. }
  236. $adminIds = $this->getDataLimitAdminIds();
  237. if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
  238. $this->error(__('You have no permission'));
  239. }
  240. if (false === $this->request->isPost()) {
  241. // 解码JSON数据
  242. if ($row['channels']) {
  243. $row['channels'] = json_decode($row['channels'], true);
  244. }
  245. if ($row['goods_ids']) {
  246. $goodsIdArr = json_decode($row['goods_ids'], true);
  247. $row['goods_ids'] = implode(',', $goodsIdArr);
  248. // 获取商品数据
  249. $goodsData = [];
  250. if (!empty($goodsIdArr)) {
  251. $goodsData = Db::name('shop_goods')
  252. ->alias('g')
  253. ->field('g.*, c.name as category_name')
  254. ->join('shop_category c', 'c.id = g.category_id', 'LEFT')
  255. ->where('g.id', 'in', $goodsIdArr)
  256. ->select();
  257. // 处理商品数据,添加category属性
  258. foreach ($goodsData as &$goods) {
  259. $goods['category'] = ['name' => $goods['category_name']];
  260. unset($goods['category_name']);
  261. }
  262. }
  263. $this->view->assign('goodsData', $goodsData);
  264. }
  265. $this->view->assign('row', $row);
  266. return $this->view->fetch();
  267. }
  268. $params = $this->request->post('row/a');
  269. if (empty($params)) {
  270. $this->error(__('Parameter %s can not be empty', ''));
  271. }
  272. $params = $this->preExcludeFields($params);
  273. // 处理活动渠道
  274. if (isset($params['channels']) && is_array($params['channels'])) {
  275. $params['channels'] = json_encode($params['channels']);
  276. } else {
  277. $params['channels'] = json_encode([]);
  278. }
  279. // 处理商品ID和商品数量
  280. $goodsIds = isset($params['goods_ids']) ? $params['goods_ids'] : '';
  281. if ($goodsIds) {
  282. $goodsIdArr = explode(',', $goodsIds);
  283. $params['goods_count'] = count($goodsIdArr);
  284. $params['goods_ids'] = json_encode($goodsIdArr);
  285. } else {
  286. $params['goods_count'] = 0;
  287. $params['goods_ids'] = '[]';
  288. }
  289. // 对于折扣活动,强制设置为指定商品参与
  290. if ($params['type'] == 'discount') {
  291. $params['goods_join_type'] = 2;
  292. }
  293. // 设置活动状态
  294. $now = time();
  295. $startTime = strtotime($params['start_time']);
  296. $endTime = strtotime($params['end_time']);
  297. if ($startTime > $now) {
  298. $params['activity_status'] = 0; // 未开始
  299. } elseif ($startTime <= $now && $endTime > $now) {
  300. $params['activity_status'] = 1; // 进行中
  301. } else {
  302. $params['activity_status'] = 2; // 已结束
  303. }
  304. $result = false;
  305. Db::startTrans();
  306. try {
  307. //是否采用模型验证
  308. if ($this->modelValidate) {
  309. $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  310. $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
  311. $row->validateFailException()->validate($validate);
  312. }
  313. $result = $row->allowField(true)->save($params);
  314. // 处理折扣数据
  315. if ($params['type'] == 'discount') {
  316. // 处理商品信息数组
  317. $goodsInfo = isset($params['goods_info']) ? json_decode($params['goods_info'], true) : [];
  318. \think\Log::write('编辑时商品信息数组: ' . json_encode($goodsInfo), 'debug');
  319. // 删除旧的规格折扣数据
  320. Db::name('shop_activity_sku')->where('activity_id', $ids)->delete();
  321. // 准备新的规格折扣数据
  322. if (!empty($goodsInfo)) {
  323. $specsData = [];
  324. foreach ($goodsInfo as $goodsItem) {
  325. if (!isset($goodsItem['goods_id'])) {
  326. continue;
  327. }
  328. $goodsId = $goodsItem['goods_id'];
  329. // 查询商品信息
  330. $goods = Db::name('shop_goods')->where('id', $goodsId)->find();
  331. if (!$goods) {
  332. continue;
  333. }
  334. if ($goodsItem['spec_type'] == 0) { // 单规格商品
  335. if (!isset($goodsItem['discount_price']) || !isset($goodsItem['discount_stocks'])) {
  336. continue;
  337. }
  338. // 获取单规格商品的实际SKU ID
  339. $skuId = isset($goodsItem['sku_id']) ? $goodsItem['sku_id'] : 0;
  340. if ($skuId == 0) {
  341. // 如果没有传SKU ID,查询商品的第一个SKU
  342. $sku = Db::name('shop_goods_sku')->where('goods_id', $goodsId)->find();
  343. $skuId = $sku ? $sku['id'] : 0;
  344. }
  345. $specsData[] = [
  346. 'activity_id' => $ids,
  347. 'goods_id' => $goodsId,
  348. 'sku_id' => $skuId, // 使用实际的SKU ID
  349. 'discount' => $goodsItem['discount'] ?: round($goodsItem['discount_price'] * 10 / $goods['price'], 1),
  350. 'discount_price' => $goodsItem['discount_price'],
  351. 'stocks' => $goodsItem['discount_stocks'],
  352. 'createtime' => time(),
  353. 'updatetime' => time(),
  354. ];
  355. } else if ($goodsItem['spec_type'] == 1 && isset($goodsItem['spec'])) { // 多规格商品
  356. foreach ($goodsItem['spec'] as $spec) {
  357. if (!isset($spec['sku_id']) || !isset($spec['discount_price']) || !isset($spec['discount_stocks'])) {
  358. continue;
  359. }
  360. // 查询规格原始价格
  361. $skuInfo = Db::name('shop_goods_sku')
  362. ->where(['id' => $spec['sku_id']])
  363. ->find();
  364. if ($skuInfo) {
  365. $specsData[] = [
  366. 'activity_id' => $ids,
  367. 'goods_id' => $goodsId,
  368. 'sku_id' => $spec['sku_id'],
  369. 'discount' => $spec['discount'] ?: round($spec['discount_price'] * 10 / $skuInfo['price'], 1),
  370. 'discount_price' => $spec['discount_price'],
  371. 'stocks' => $spec['discount_stocks'],
  372. 'createtime' => time(),
  373. 'updatetime' => time(),
  374. ];
  375. }
  376. }
  377. }
  378. }
  379. // 批量插入规格折扣数据
  380. if (!empty($specsData)) {
  381. Db::name('shop_activity_sku')->insertAll($specsData);
  382. }
  383. }
  384. }
  385. Db::commit();
  386. } catch (ValidateException|PDOException|Exception $e) {
  387. Db::rollback();
  388. $this->error($e->getMessage());
  389. }
  390. if (false === $result) {
  391. $this->error(__('No rows were updated'));
  392. }
  393. $this->success();
  394. }
  395. /**
  396. * 手动停止活动
  397. */
  398. public function stopActivity()
  399. {
  400. $id = $this->request->post('id');
  401. $activity = $this->model->find($id);
  402. if (!$activity) {
  403. $this->error('活动不存在');
  404. }
  405. if ($activity['activity_status'] != 1) {
  406. $this->error('只有进行中的活动才能手动停止');
  407. }
  408. // 设置停止时间和状态
  409. $activity->stop_time = date('Y-m-d H:i:s');
  410. $activity->activity_status = 3; // 手动停止
  411. if ($activity->save()) {
  412. $this->success('活动已手动停止');
  413. } else {
  414. $this->error('操作失败');
  415. }
  416. }
  417. /**
  418. * 更新活动状态
  419. * 可作为定时任务
  420. */
  421. public function updateActivityStatus()
  422. {
  423. $now = date('Y-m-d H:i:s');
  424. // 更新未开始的活动
  425. Db::name('shop_discount')
  426. ->where([
  427. 'status' => 1, // 启用状态
  428. 'activity_status' => ['IN', [0, 3]], // 未开始或手动停止
  429. 'start_time' => ['<=', $now],
  430. 'end_time' => ['>', $now],
  431. 'stop_time' => ['exp', Db::raw('IS NULL OR stop_time > NOW()')],
  432. ])
  433. ->update(['activity_status' => 1]); // 更新为进行中
  434. // 更新已结束的活动
  435. Db::name('shop_discount')
  436. ->where([
  437. 'status' => 1, // 启用状态
  438. 'activity_status' => 1, // 进行中
  439. ])
  440. ->where(function($query) use ($now) {
  441. $query->where('end_time', '<=', $now)
  442. ->whereOr('stop_time', '<=', $now);
  443. })
  444. ->update(['activity_status' => 2]); // 更新为已结束
  445. $this->success('活动状态更新完成');
  446. }
  447. /**
  448. * 获取活动商品的折扣和库存数据
  449. */
  450. public function get_discount_specs()
  451. {
  452. $discountId = $this->request->get('discount_id');
  453. if (!$discountId) {
  454. $this->error('参数错误');
  455. }
  456. // 查询折扣数据
  457. $discountSpecs = Db::name('shop_activity_sku_prize')
  458. ->where('discount_id', $discountId)
  459. ->select();
  460. $this->success('', null, $discountSpecs);
  461. }
  462. }