Discount.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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.*')
  258. ->where('g.id', 'in', $goodsIdArr)
  259. ->select();
  260. // 处理商品数据,添加category属性
  261. // foreach ($goodsData as &$goods) {
  262. // $goods['category'] = ['name' => $goods['category_name']];
  263. // unset($goods['category_name']);
  264. // }
  265. }
  266. $this->view->assign('goodsData', $goodsData);
  267. }
  268. $this->view->assign('row', $row);
  269. return $this->view->fetch();
  270. }
  271. $params = $this->request->post('row/a');
  272. if (empty($params)) {
  273. $this->error(__('Parameter %s can not be empty', ''));
  274. }
  275. $params = $this->preExcludeFields($params);
  276. // 处理活动渠道
  277. if (isset($params['channels']) && is_array($params['channels'])) {
  278. $params['channels'] = json_encode($params['channels']);
  279. } else {
  280. $params['channels'] = json_encode([]);
  281. }
  282. // 处理商品ID和商品数量
  283. $goodsIds = isset($params['goods_ids']) ? $params['goods_ids'] : '';
  284. if ($goodsIds) {
  285. $goodsIdArr = explode(',', $goodsIds);
  286. $params['goods_count'] = count($goodsIdArr);
  287. $params['goods_ids'] = json_encode($goodsIdArr);
  288. } else {
  289. $params['goods_count'] = 0;
  290. $params['goods_ids'] = '[]';
  291. }
  292. // 对于折扣活动,强制设置为指定商品参与
  293. if ($params['type'] == 'discount') {
  294. $params['goods_join_type'] = 2;
  295. }
  296. // 设置活动状态
  297. $now = time();
  298. $startTime = strtotime($params['start_time']);
  299. $endTime = strtotime($params['end_time']);
  300. if ($startTime > $now) {
  301. $params['activity_status'] = 0; // 未开始
  302. } elseif ($startTime <= $now && $endTime > $now) {
  303. $params['activity_status'] = 1; // 进行中
  304. } else {
  305. $params['activity_status'] = 2; // 已结束
  306. }
  307. $result = false;
  308. Db::startTrans();
  309. try {
  310. //是否采用模型验证
  311. if ($this->modelValidate) {
  312. $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  313. $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
  314. $row->validateFailException()->validate($validate);
  315. }
  316. $result = $row->allowField(true)->save($params);
  317. // 处理折扣数据
  318. if ($params['type'] == 'discount') {
  319. // 处理商品信息数组
  320. $goodsInfo = isset($params['goods_info']) ? json_decode($params['goods_info'], true) : [];
  321. \think\Log::write('编辑时商品信息数组: ' . json_encode($goodsInfo), 'debug');
  322. // 删除旧的规格折扣数据
  323. Db::name('shop_activity_sku')->where('activity_id', $ids)->delete();
  324. // 准备新的规格折扣数据
  325. if (!empty($goodsInfo)) {
  326. $specsData = [];
  327. foreach ($goodsInfo as $goodsItem) {
  328. if (!isset($goodsItem['goods_id'])) {
  329. continue;
  330. }
  331. $goodsId = $goodsItem['goods_id'];
  332. // 查询商品信息
  333. $goods = Db::name('shop_goods')->where('id', $goodsId)->find();
  334. if (!$goods) {
  335. continue;
  336. }
  337. if ($goodsItem['spec_type'] == 0) { // 单规格商品
  338. if (!isset($goodsItem['discount_price']) || !isset($goodsItem['discount_stocks'])) {
  339. continue;
  340. }
  341. // 获取单规格商品的实际SKU ID
  342. $skuId = isset($goodsItem['sku_id']) ? $goodsItem['sku_id'] : 0;
  343. if ($skuId == 0) {
  344. // 如果没有传SKU ID,查询商品的第一个SKU
  345. $sku = Db::name('shop_goods_sku')->where('goods_id', $goodsId)->find();
  346. $skuId = $sku ? $sku['id'] : 0;
  347. }
  348. $specsData[] = [
  349. 'activity_id' => $ids,
  350. 'goods_id' => $goodsId,
  351. 'sku_id' => $skuId, // 使用实际的SKU ID
  352. 'discount' => $goodsItem['discount'] ?: round($goodsItem['discount_price'] * 10 / $goods['price'], 1),
  353. 'discount_price' => $goodsItem['discount_price'],
  354. 'stocks' => $goodsItem['discount_stocks'],
  355. 'createtime' => time(),
  356. 'updatetime' => time(),
  357. ];
  358. } else if ($goodsItem['spec_type'] == 1 && isset($goodsItem['spec'])) { // 多规格商品
  359. foreach ($goodsItem['spec'] as $spec) {
  360. if (!isset($spec['sku_id']) || !isset($spec['discount_price']) || !isset($spec['discount_stocks'])) {
  361. continue;
  362. }
  363. // 查询规格原始价格
  364. $skuInfo = Db::name('shop_goods_sku')
  365. ->where(['id' => $spec['sku_id']])
  366. ->find();
  367. if ($skuInfo) {
  368. $specsData[] = [
  369. 'activity_id' => $ids,
  370. 'goods_id' => $goodsId,
  371. 'sku_id' => $spec['sku_id'],
  372. 'discount' => $spec['discount'] ?: round($spec['discount_price'] * 10 / $skuInfo['price'], 1),
  373. 'discount_price' => $spec['discount_price'],
  374. 'stocks' => $spec['discount_stocks'],
  375. 'createtime' => time(),
  376. 'updatetime' => time(),
  377. ];
  378. }
  379. }
  380. }
  381. }
  382. // 批量插入规格折扣数据
  383. if (!empty($specsData)) {
  384. Db::name('shop_activity_sku')->insertAll($specsData);
  385. }
  386. }
  387. }
  388. Db::commit();
  389. } catch (ValidateException|PDOException|Exception $e) {
  390. Db::rollback();
  391. $this->error($e->getMessage());
  392. }
  393. if (false === $result) {
  394. $this->error(__('No rows were updated'));
  395. }
  396. $this->success();
  397. }
  398. /**
  399. * 手动停止活动
  400. */
  401. public function stopActivity()
  402. {
  403. $id = $this->request->post('id');
  404. $activity = $this->model->find($id);
  405. if (!$activity) {
  406. $this->error('活动不存在');
  407. }
  408. if ($activity['activity_status'] != 1) {
  409. $this->error('只有进行中的活动才能手动停止');
  410. }
  411. // 设置停止时间和状态
  412. $activity->stop_time = date('Y-m-d H:i:s');
  413. $activity->activity_status = 3; // 手动停止
  414. if ($activity->save()) {
  415. $this->success('活动已手动停止');
  416. } else {
  417. $this->error('操作失败');
  418. }
  419. }
  420. /**
  421. * 更新活动状态
  422. * 可作为定时任务
  423. */
  424. public function updateActivityStatus()
  425. {
  426. $now = date('Y-m-d H:i:s');
  427. // 更新未开始的活动
  428. Db::name('shop_discount')
  429. ->where([
  430. 'status' => 1, // 启用状态
  431. 'activity_status' => ['IN', [0, 3]], // 未开始或手动停止
  432. 'start_time' => ['<=', $now],
  433. 'end_time' => ['>', $now],
  434. 'stop_time' => ['exp', Db::raw('IS NULL OR stop_time > NOW()')],
  435. ])
  436. ->update(['activity_status' => 1]); // 更新为进行中
  437. // 更新已结束的活动
  438. Db::name('shop_discount')
  439. ->where([
  440. 'status' => 1, // 启用状态
  441. 'activity_status' => 1, // 进行中
  442. ])
  443. ->where(function($query) use ($now) {
  444. $query->where('end_time', '<=', $now)
  445. ->whereOr('stop_time', '<=', $now);
  446. })
  447. ->update(['activity_status' => 2]); // 更新为已结束
  448. $this->success('活动状态更新完成');
  449. }
  450. /**
  451. * 获取活动商品的折扣和库存数据
  452. */
  453. public function get_discount_specs()
  454. {
  455. $discountId = $this->request->get('discount_id');
  456. if (!$discountId) {
  457. $this->error('参数错误');
  458. }
  459. // 查询折扣数据
  460. $discountSpecs = Db::name('shop_activity_sku_prize')
  461. ->where('discount_id', $discountId)
  462. ->select();
  463. $this->success('', null, $discountSpecs);
  464. }
  465. }